Microsoft .NET Code Analysis: Always Add Braces {} in C#

Recently, a fellow Microsoft MVP posted a tweet, inquiring about the usage of braces in statements in C#. I’m not sure if she was genuinely seeking answers or simply looking to initiate a discussion. I must admit that this tweet did leave me a bit frustrated because I believed this matter had already been firmly established, especially considering that this book has been in existence for almost 20 years!

I’m not aware of why the C# team permitted this practice during the language’s design in the late 90s. In contrast, this isn’t a concern in languages like VB.NET because it’s not allowed.

Not adding braces {} to if statements can lead to issues and affect code readability. The following code demonstrates a violation of this practice:

if (somelist[i] != other.somelist[i])
    return false;

This can lead to significant problems, as exemplified by Apple’s experience with iOS 7.0.6. This particular security update inadvertently introduced a vulnerability that enabled a Man-in-the-Middle (MitM) attack. This is how you fix it:

if (somelist[i] != other.somelist[i])
{
    return false;
}

It is crucial to always include braces when writing if statements. Here are several reasons that highlight the importance of using braces:

  1. Defining code blocks: Braces are used to enclose a block of code, such as a method, a loop, a conditional statement, or a class. They determine the beginning and end of the block, providing a clear visual indication of where the block starts and ends. This helps maintain code organization and readability.
  2. Grouping statements: Braces allow you to group multiple statements together within a block. For example, within a method, you might have multiple lines of code that need to be executed together. By enclosing these statements in braces, you ensure that they are treated as a single unit.
  3. Controlling flow and scoping: Braces play a crucial role in controlling the flow of execution and determining the scope of variables. For instance, in an if statement, braces are used to define the block of code that should be executed if the condition is true. Similarly, in a loop, braces define the block of code that is repeated until the loop condition is no longer true.
  4. Code readability and maintenance: By consistently using braces, you make your code more readable and less prone to errors. The use of braces clearly separates different blocks of code and eliminates ambiguity. It also makes it easier to add or remove statements within a block without accidentally changing the intended scope.
  5. Avoiding unintended consequences: Omitting braces can lead to unintended consequences and bugs, particularly when working with nested control structures like loops and conditionals. Without braces, only the immediately following statement is considered part of the block, which can lead to misunderstandings and incorrect behavior.

When I setup the IDE0011 and other code analysis settings in my .editorConfig it looks like this:
dotnet_diagnostic.IDE0011.severity = error
csharp_prefer_braces = true: error
dotnet_diagnostic.SA1500.severity = warning
dotnet_diagnostic.SA1503.severity = warning
dotnet_diagnostic.SA1520.severity = warning

Summary

During my review of a codebase, I identified 38 instances where this issue occurs. Considering the refactoring required, it is essential to streamline the process. Tools like CodeRush from DevExpress offer valuable extensions that simplify the refactoring task with a single mouse click, making the process efficient and convenient.

Numerous settings in the code refactoring tool CodeRush can be adjusted to ensure consistent brace usage. If you utilize CodeRush or ReSharper, I highly recommend integrating these settings with those in your EditorConfig file.

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.

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.

One thought on “Microsoft .NET Code Analysis: Always Add Braces {} in C#

  1. Typical errors like (let’s take Apple example)

    if (a); // <- unwanted ; here
    goto fail;

    or

    if (a)
    goto fail;
    goto fail; // <- incorrect

    can be easily find out by static code analysis and covered by tests (it’s a question to Apple – how can they tolerate “unreachable code detected” – do they ignore warnings? What else warning do they ignore? Do they perform static code analysis at all?). What matters most is, IMHO, readability. Unwanted {…} is a visual garbage either in math 2 + 3 * 4 + 5 * 6 vs. ((2 + (3 * 4)) + (5 * 6)) and programming:

    foreach (int num in nums)
    if (num > 0 )
    result += num;

    vs. (note bloated code – 7 lines instead of 3 – where 4 lines are just { or })

    foreach (int num in nums)
    {
    if (num > 0 )
    {
    result += num;
    }
    }

Leave a comment

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