cleansharp.NET
"Clean code always looks like it was written by someone who cares."— Robert C. Martin (Uncle Bob)
Always use curly braces, even for one-liners — clarity beats cleverness.
Leaving out curly braces in control statements like if
, for
, or while
can make your code shorter but also more error-prone.
It’s easy to introduce bugs when new lines are added without realizing they’re outside the intended scope. Curly braces make the control flow crystal clear.
This code might look fine — until someone adds a logging line thinking it’s part of the if
block:
if (user.IsActive)
SendWelcomeEmail(user);
Log.Info("Welcome email sent."); // ⚠️
Only the first line runs conditionally. The log always runs — even if the user isn’t active.
With braces, it’s obvious what belongs in the if
block — and mistakes like the one above are avoided.
if (user.IsActive)
{
SendWelcomeEmail(user);
Log.Info("Welcome email sent.");
}
Apple’s infamous goto fail bug in 2014 happened because of a missing brace. It compromised SSL verification in macOS and iOS — all from a subtle indentation mistake.
Braces could have prevented it.
To enforce this rule in your project, add the following to your .editorconfig
file:
csharp_prefer_braces = true
dotnet_diagnostic.IDE0011.severity = warning
This will make the compiler treat missing braces as a warning, ensuring consistent code style across your team.