Microsoft .NET Code Analysis: Properly Formatting Class Files

One common issue I often encounter when reviewing code is inconsistent formatting of class files. It is of utmost importance that these files are formatted consistently, making them easier to read and understand. Maintaining a uniform format across all class files is essential for better collaboration among developers, irrespective of who wrote the code.

To ensure consistent formatting, you can utilize Visual Studio’s convenient feature by pressing CTRL-K, CTRL-D. Additionally, you can set up the following rules in your EditorConfig file to enforce proper formatting:

When I setup the IDE0055 code analysis in my .editorConfig it looks like this: dotnet_diagnostic.IDE0055.severity = suggestion

I often come across projects that neglect proper class formatting. For instance, this particular issue recurs more than 8,000 times in the EntityFramework source code!

Improving Readability with Using Directive Options

For enhanced readability and easier comprehension of directives, consider employing the following setting to prioritize system directives, thus sorting them first:

[*.{cs,vb}]
dotnet_sort_system_directives_first = true

C# Formatting Options

Below, I will showcase the C# formatting options I employ in my EditorConfig file.

New Line Before Open Brace

I like this setting to keep my files organized. It ensures there is a new line before an open brace for the following elements:

  • Accessors
  • Anonymous methods
  • Anonymous types
  • Control blocks
  • Events
  • Indexers
  • Lambdas
  • Local functions
  • Methods
  • Object collection array initializers
  • Properties
  • Types

To enable this setting, use the option provided below.

[*.cs]
csharp_new_line_before_open_brace = all

New Line Before “else”

To ensure there is a new line before the “else” keyword in an if statement, use the setting below.

csharp_new_line_before_else = true

With this setting enabled, your if statements will appear as follows:

if (rule.AccessControlType == AccessControlType.Allow)
{
    allow = true;
}
else if (rule.AccessControlType == AccessControlType.Deny)
{
    deny = true;
}

New Line Before “catch”

To ensure that there is a new line before the catch block of a try/catch, use the setting below.

csharp_new_line_before_catch = true

When using this setting, your catch block will appear as follows:

try
{
    value = JsonSerializer.Deserialize<T>(BitConverter.ToString(bytes));
    return true;
}
catch (ArgumentNullException)
{
    value = default;
    return false;
}

New Line Before “finally”

To ensure that the finally block in try/catch is on its own line, use the setting below.

csharp_new_line_before_finally = true

New Line Before Members in Object Initializers

For readability, when using object initializers, it’s advisable to format each member on a new line, as shown below.

var options = new EnumerationOptions
{
    IgnoreInaccessible = true,
    ReturnSpecialDirectories = false,
    RecurseSubdirectories = false
};

To ensure that object initializers are formatted correctly, use the setting below.

csharp_new_line_before_members_in_object_initializers = true

New Line Before Members in Anonymous Types

Just like members in object initializers, the same formatting should apply to anonymous types as well. Use the setting below.

csharp_new_line_before_members_in_anonymous_types = true

New Line Between Query Expression Clauses

If you use the LINQ API, it’s advisable to put each expression clause on its own line. See the example below on how I format LINQ API statements:

var query = from
              p in people
            where 
              (p.Age.TotalDays / 365) > 30 &&
              p.City == "Los Angeles"
            select new
            {
              Name = string.Format("{0} {1}", p.FirstName, p.LastName),
              Email = p.Email
            };

As you can see, each clause starts on a new line. By placing each clause on a separate line, the code becomes more readable and easier to maintain. It helps to visually distinguish each part of the query, making it clearer for others to understand the logic behind it. Use this setting below.

csharp_new_line_between_query_expression_clauses = true

Indentation Options

In C#, it’s essential to maintain consistent indentation. Here is how I have it set up in my EditorConfig file.

csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true

Spacing Options

Equally important are spacing options too. There are a lot of them for C#; below is how I have them configured in my EditorConfig file.

csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements   = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets  = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses  = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses   = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false

Wrap Options

The wrap formatting options concern the utilization of single lines versus separate lines for statements and code blocks. Here is how I have configured this in my EditorConfig file.

csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = false

Formatting Files with CodeRush

CodeRush is a powerful code refactoring tool developed by DevExpress, which I have been using exclusively for refactoring purposes since its release. One of the standout features of CodeRush is its flexible formatting options, which can be easily configured to suit your preferences. By default, it adheres to the settings specified in your EditorConfig file, but it also offers additional customization options to go above and beyond those defaults.

CodeRush offers a wide array of formatting options, making it an ideal choice for teams working together. One of its time-saving features is the Code Cleanup settings, which can automatically apply the chosen formatting options whenever you save a file – a feature I personally prefer and find very convenient.

Another indispensable feature I rely on before committing code is the ability to organize the layout of class file elements. This ensures that the files are not only easy to read but also simple to modify. By default, CodeRush organizes elements according to the StyleCop standards, which aligns with the formatting guidelines I advocate in my book “Rock Your Code: Coding Standards for Microsoft .NET,” available on Amazon. You can configure CodeRush to perform this organization on each save, or you can manually trigger it by right-clicking anywhere in the file and selecting “Organize Members,” as illustrated below. This flexibility allows for seamless integration into your coding workflow.

This automatic consistency in formatting keeps my class files looking neat and organized without any extra effort! And the best part is, it comes absolutely free!  

Summary

I’d like to point out that most of the settings mentioned in this article do not pertain to using VB.NET, as its editors automatically handle formatting classes to look the same. This is actually one of the reasons I personally like VB.NET (please keep it between us!).

I have written more about formatting class files in the article below:

For further guidance and insights, I highly recommend obtaining a copy of my book, “Rock Your Code: Coding Standards for Microsoft .NET” available on Amazon.com. Additionally, to explore more performance tips for .NET, I encourage you to acquire the 3rd edition of “Rock Your Code: Code & App Performance for Microsoft .NET” also available on Amazon.com.

To analyze your code using the same settings I used in these articles, I encourage you to incorporate my EditorConfig file. It can be found at the following link: https://bit.ly/dotNetDaveEditorConfig. I update this file quarterly, so remember to keep yours up to date as well. I hope you will check out my OSS project Spargine by using this link: https://bit.ly/Spargine.

To download CodeRush from DevExpress, use this link: https://www.devexpress.com/products/coderush/.

Please feel free to leave a comment below. I would appreciate hearing your thoughts and feedback.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.