Wednesday, May 10, 2023

Visual Studio 2022: Apply File Scoped Namespaces using Code Cleanup Profile

In this post, let's see how we can apply File scoped namespaces to all the existing C# files using a Code Cleanup Profile.

Imagine you have an old .NET project that uses Block scoped namespaces and you are upgrading the project to the latest .NET and you need to use features like File scoped namespaces that got introduced as part of C# 10.0. If you have many files, you definitely don't need to be updating files one by one.

We can apply this change to all the files at once using a Visual Studio Code Cleanup profile.

First, we need to set Namespace declarations code style preference to File scoped (if you haven't already) by going into Tools -> Options -> Text Editor -> C# -> Code Style -> General.
Update Code Style
Then go to Analyse -> Code Cleanup -> Configure Code Cleanup and configure your profile, adding the following preference.
Configure Code Cleanup
You can create a new profile just for this or update an existing profile. And then just run your Code Cleanup profile. That should update all your files with File scoped namespaces.

Hope this helps.

Happy Coding.


No comments:

Post a Comment