Enforce code cleanup on build — .Net

.NET CODE ANALYSIS

Create code cleanup profiles and run on the build-in Visual Studio.

Photo by Blake Connally on Unsplash


The article demonstrates how

  1. To create code cleanup profiles in the Visual Studio solution explorer.

  2. Run code cleanup profile manually or automatically on the build.

  3. How some of the Visual Studio 2019 code analysis features can improve the quality of our C# code and save us a lot of time cleaning up and organizing code.

Prerequisites

  1. Install latest visual studio community edition.

Getting Started

Open any .Net Framework or .Net project in the Visual Studio.

Step 1: Open Code Cleanup Profiles

Right-click on solution or project and go to “Analyze and Code Cleanup” and click “Configure Code Cleanup.”

Step 2: Configure Profiles

Move available fixers from the bottom panel to the “Included Fixers” panel and click “OK.”

Most commonly used fixers:

  1. Remove unnecessary casts, i.e., to remove where typecasting is not required.

  2. Apply expression/block body preference

  3. Remove unused variables, i.e., remove the variables that are declared but never used.

  4. Remove unnecessary using, i.e., to remove the imports that are no longer used in the “.cs” files.

Step 3: Run profile manually

Right-click on solution or project and go to “Analyze and Code Cleanup” and click “Run Code Cleanup (Profile 1)” or whichever profile is configured on Step 2. As shown in below screenshot.

Step 4: Run profile automatically

.NET code style analysis is disabled by default, on build for all .NET projects. You can enable code style analysis for .NET projects by setting the EnforceCodeStyleInBuild property to true.

<PropertyGroup>
  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

After this project code cleanup will run automatically on the project or solution build.

Customize Visual Studio code analysis settings

Every company has specific code styling guidelines, and it may be that the default Visual Studio settings for code analyzing don’t meet those preferences. For example, some companies favor using braces even when they implement them to a single line, while others prefer not to use them.

No braces

if (condition)
    Console.WriteLine(text);

With braces

if (condition){
    Console.WriteLine(text);
}

Configuration path in Visual Studio: Select Tools > Options > Text Editor > C#.

Thank you for reading and hope you liked the article. Follow me on LinkedIn Instagram Facebook Twitter

Stay tuned on C#

View at Medium.com

#VisualStudio #CodeAnalysis #DotnetCore #Dotnet #CodeReview

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w