Layout and Formatting¶
Rule prefix: FMT · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
Home · Rule index · Naming cheat sheet
This chapter sets how a C# file looks: indentation and encoding, braces, spacing, line length and wrapping, blank lines, initializers, parentheses, and the structure of a file (namespace, using directives, one type per file). Names are set on pages 02 to 04, var and declarations on pages 05 and 06, member order and modifier order on page 08, and comments on page 09.
Most rules here are checked by one IDE rule, IDE0055, which compares a file with the formatting options of the shipped .editorconfig. The build reports a wrongly indented line at the end of the line above it, so the incorrect examples for indentation put their comment on that line above. Rules that no analyzer reports in the build (line length, wrapping, trailing commas, using order, one type per file, #region) are checked in review or by the editor; the Manual rules among them are listed in the "Manual review only" table on page 15.
Rule index¶
| ID | Level | Rule | Enforced |
|---|---|---|---|
| FMT-010 | DO | indent with four spaces and no tabs, save C# files as UTF-8 with a byte-order mark, end every file with a newline and leave no whitespace at the end of a line. | IDE0055 |
| FMT-020 | DO | put every opening brace and every closing brace on a line of its own (Allman style); a one-line block is allowed only for an accessor list such as { get; init; } and for an empty body { }. |
IDE0055 |
| FMT-021 | DO | enclose the body of every if, else, for, foreach, while, do, using, lock and fixed statement in braces, even when the body is a single statement. |
IDE0011, ReSharper: EnforceIfStatementBraces |
| FMT-022 | DO | start else, catch and finally on a new line below the closing brace of the preceding block. |
IDE0055 |
| FMT-023 | DO | indent the contents of every block one level (four spaces) deeper than its braces, and indent the braces at the level of the statement or declaration that owns them. | IDE0055 |
| FMT-024 | DO | indent case and default labels one level inside the switch braces and the statements of each section one level below its label, without an extra level for braces around a section. |
IDE0055 |
| FMT-030 | DO | put one space after control-flow keywords (if, for, foreach, while, switch, catch), after commas and for-loop semicolons, around binary operators and on both sides of the colon in a base-type list. |
IDE0055 |
| FMT-031 | DO NOT | put a space inside parentheses or square brackets, after a cast, before or after a ., or between a method name and its opening parenthesis in a declaration or a call. |
IDE0055 |
| FMT-032 | DO NOT | insert extra spaces to line up names, = signs or end-of-line comments across consecutive lines. |
IDE0055 |
| FMT-040 | DO | keep every line at or below 120 characters, counting indentation. | Manual |
| FMT-041 | DO | wrap a line that is longer than 120 characters before a binary operator or before each . of a chained call; keep an argument or parameter list on one line when the call or declaration fits in 120 characters, and otherwise wrap it after the last item that fits (one item per line after the opening parenthesis is also accepted); wrap an expression body that does not fit before or after =>; indent each continuation line four spaces. |
Manual |
| FMT-042 | DO | put each statement on its own line, including short statements such as i++; or break;. |
IDE0055 |
| FMT-043 | DO | separate adjacent methods, properties with bodies, constructors and nested types with exactly one blank line, and never put two blank lines in a row anywhere in a file. | IDE2000 |
| FMT-044 | DO NOT | leave a blank line directly after an opening brace, directly before a closing brace, or between two consecutive closing braces. | IDE2002, ReSharper: IncorrectBlankLinesNearBraces |
| FMT-045 | DO | put exactly one blank line after the last using directive and one after the file-scoped namespace declaration. |
IDE0055 |
| FMT-046 | DO | put one blank line before a return, throw, break, continue, goto or yield break statement, unless it is the first statement in its block or directly follows a label (case, default or a statement label); when comments sit directly above the statement, put the blank line above the comments. |
ReSharper: SeparateControlTransferStatement |
| FMT-050 | DO | put each member assignment of a multi-line object initializer or anonymous type, and each arm of a multi-line switch expression, on its own line. | IDE0055 |
| FMT-051 | CONSIDER | add parentheses where an expression mixes arithmetic, relational or logical operators of different precedence (a + (b * c)), and remove parentheses that clarify nothing. |
IDE0047, IDE0048 |
| FMT-052 | DO NOT | put a comma after the last element of an object or collection initializer, collection expression, enum or switch expression. | ReSharper: ArrangeTrailingCommaInMultilineLists |
| FMT-060 | DO | declare the namespace of a file with a file-scoped declaration (namespace Contoso.Orders;), not with a braced namespace block. |
IDE0161, ReSharper: ArrangeNamespaceBody |
| FMT-061 | DO | place every using directive at the top of the file, before the namespace declaration and outside any namespace. |
IDE0065 |
| FMT-062 | DO | order using directives either with System namespaces first and the rest alphabetically, or all alphabetically, with no blank lines between groups, followed by using aliases and then all using static directives at the end, each group in alphabetical order. |
Manual |
| FMT-063 | DO | delete every using directive the file does not need, including directives for namespaces that implicit global usings already import (System, System.Linq, System.Threading.Tasks and the others), and declare global using directives only in one GlobalUsings.cs per project or as <Using> items in the project file. |
IDE0005, ReSharper: RedundantUsingDirective |
| FMT-064 | DO | declare exactly one top-level type in each file; nested types and file-local helper types stay with the type that uses them. | Manual |
| FMT-065 | DO | name each source file exactly after the single top-level type it contains, with the same casing (OrderService.cs for OrderService); generic types and partial types follow NAM-033 and NAM-034. |
Manual |
| FMT-066 | DO NOT | use #region and #endregion in hand-written code; split a type that needs regions into smaller types or partial files instead. |
Manual |
Files and indentation¶
These rules set indentation, encoding and file endings.
FMT-010¶
DO indent with four spaces and no tabs, save C# files as UTF-8 with a byte-order mark, end every file with a newline and leave no whitespace at the end of a line.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderTotals
{
public decimal Net { get; init; }
}
✅ Correct — the matching settings
[*]
indent_style = space
indent_size = 4
tab_width = 4
insert_final_newline = true
trim_trailing_whitespace = true
[*.cs]
charset = utf-8-bom
❌ Incorrect — one member indented with a tab, another with two spaces
namespace Contoso.Orders;
public sealed class OrderTotals
{ // The next line is indented with a tab.
public decimal Net { get; init; }
}
public sealed class OrderSummary
{ // The next line is indented with two spaces.
public decimal Gross { get; init; }
}
Why: The width of a tab differs between editors, diff views and review tools, so four spaces are the only indentation that looks the same everywhere. The BOM tells tools that read raw bytes that the file is UTF-8; the EditorConfig documentation and the Roslyn repository both use utf-8-bom for C# files. A final newline keeps a diff from reporting "no newline at end of file" when a line is appended, and trailing whitespace shows up in diffs as a change to a line that looks unchanged. IDE0055 reports tab and space indentation in the build. The Google guide uses two-space indentation. No end_of_line value is pinned, because the Microsoft sources disagree and ReSharper ignores the key.
Exceptions:
end_of_lineis not set. Normalize line endings with.gitattributes(* text=auto).
Scope: All C# source files (*.cs); indentation applies to every file type in config/.editorconfig · Enforced: IDE0055 · Config: indent_style, indent_size, tab_width, trim_trailing_whitespace, insert_final_newline, charset · Sources: MS-CONV, MS-DOCS-EC, RT-EC, ROSLYN, MS-IDE-CSFMT
Braces¶
The Allman style rules (FMT-020 to FMT-024) share one setting family. Their incorrect examples each break one setting.
FMT-020¶
DO put every opening brace and every closing brace on a line of its own (Allman style); a one-line block is allowed only for an accessor list such as { get; init; } and for an empty body { }.
✅ Correct
public static decimal Sum(IReadOnlyList<OrderLine> lines)
{
decimal sum = 0m;
foreach (OrderLine line in lines)
{
if (line.Quantity > 0)
{
sum += line.Amount;
}
}
return sum;
}
❌ Incorrect — the opening brace stays on the declaration line
namespace Contoso.Orders;
public sealed class OrderTotals { // Opening brace on the declaration line.
public decimal Net { get; init; }
}
Why: Braces on their own lines put the start and the end of every block in the same column, so a reader finds the extent of a block by scanning down the left margin, and adding a statement changes one line in a diff. The Microsoft conventions and the Roslyn and runtime repositories use this layout. The Google guide uses K&R braces, which the Microsoft conventions do not use.
Exceptions:
- An accessor list on one line (
{ get; init; }) and an empty body ({ }).
Scope: Type, member, accessor, lambda, initializer and control-flow blocks · Enforced: IDE0055 · Config: csharp_new_line_before_open_brace, csharp_preserve_single_line_blocks, resharper_csharp_brace_style · Sources: MS-CONV, MS-IDE-CSFMT, RT-STYLE, RS-BRACES
FMT-021¶
DO enclose the body of every if, else, for, foreach, while, do, using, lock and fixed statement in braces, even when the body is a single statement.
✅ Correct
public static decimal GetLastLineAmount(Order order)
{
if (order.Lines.Count == 0)
{
return 0m;
}
return order.Lines[^1].Amount;
}
❌ Incorrect — the body of the if has no braces
public static decimal GetLastLineAmount(Order order)
{
if (order.Lines.Count == 0) // Body has no braces.
return 0m;
return order.Lines[^1].Amount;
}
Why: When the body already has braces, a line added later cannot silently fall outside it. One rule for every body also removes the judgment about which bodies are short enough to go without. The dotnet/runtime style allows omitting braces when every branch is one line.
Exceptions:
- A
usingdeclaration (using FileStream stream = File.OpenRead(path);) has no body and needs no braces. - An
else ifchain needs no extra braces around the nestedif; each of its bodies still has braces.
Scope: Bodies of if, else, for, foreach, while, do, using, lock and fixed statements · Enforced: IDE0011, ReSharper: EnforceIfStatementBraces · Config: csharp_prefer_braces, resharper_csharp_braces_for_ifelse, resharper_csharp_braces_for_for, resharper_csharp_braces_for_foreach, resharper_csharp_braces_for_while, resharper_csharp_braces_for_dowhile, resharper_csharp_braces_for_using, resharper_csharp_braces_for_lock, resharper_csharp_braces_for_fixed, resharper_enforce_if_statement_braces_highlighting, resharper_enforce_for_statement_braces_highlighting, resharper_enforce_foreach_statement_braces_highlighting, resharper_enforce_while_statement_braces_highlighting, resharper_enforce_do_while_statement_braces_highlighting, resharper_enforce_using_statement_braces_highlighting, resharper_enforce_lock_statement_braces_highlighting, resharper_enforce_fixed_statement_braces_highlighting · Sources: MS-IDE, SA, AV, RS-BRACES-STYLE, RT-STYLE
FMT-022¶
DO start else, catch and finally on a new line below the closing brace of the preceding block.
✅ Correct
public static void Process(Order order, OrderLine line)
{
if (order.IsShipped)
{
Console.WriteLine("Already shipped.");
}
else
{
order.AddLine(line);
}
}
✅ Correct — catch and finally
string path = "orders.json";
try
{
string json = File.ReadAllText(path);
Console.WriteLine(json.Length);
}
catch (IOException)
{
Console.WriteLine("The file could not be read.");
}
finally
{
Console.WriteLine("Done.");
}
❌ Incorrect — else on the line of the closing brace
public static void Process(Order order, OrderLine line)
{
if (order.IsShipped)
{
Console.WriteLine("Already shipped.");
} else // The else keyword is on the closing-brace line.
{
order.AddLine(line);
}
}
Why: else, catch and finally then begin a line like every other statement keyword, so a brace never shares a line with code, and the Allman rule (FMT-020) has no second layout for the same block.
Scope: else, catch and finally clauses · Enforced: IDE0055 · Config: csharp_new_line_before_else, csharp_new_line_before_catch, csharp_new_line_before_finally · Sources: MS-IDE-CSFMT, MS-CONV
FMT-023¶
DO indent the contents of every block one level (four spaces) deeper than its braces, and indent the braces at the level of the statement or declaration that owns them.
✅ Correct
public static bool IsLarge(Order order)
{
decimal total = order.Total;
return total > 1_000m;
}
❌ Incorrect — the block contents are not indented
public static bool IsLarge(Order order)
{ // The next line is not indented.
decimal total = order.Total;
return total > 1_000m;
}
Why: When the braces sit at the level of their owner and the contents sit one level deeper, the number of indentation levels equals the nesting depth, which a reviewer can count. Indenting the braces themselves adds a level that carries no nesting.
Scope: Contents of every block · Enforced: IDE0055 · Config: csharp_indent_block_contents, csharp_indent_braces · Sources: MS-IDE-CSFMT, MS-CONV
FMT-024¶
DO indent case and default labels one level inside the switch braces and the statements of each section one level below its label, without an extra level for braces around a section.
✅ Correct
public static string Describe(OrderStatus status)
{
var text = new StringBuilder();
switch (status)
{
case OrderStatus.Pending:
text.Append("Waiting");
break;
default:
text.Append("Closed");
break;
}
return text.ToString();
}
✅ Correct — a braced section: the braces in the column of the label, the statements one level deeper
public static void Describe(OrderStatus status, StringBuilder text)
{
switch (status)
{
case OrderStatus.Pending:
{
string label = "Waiting";
text.Append(label);
break;
}
default:
text.Append("Closed");
break;
}
}
❌ Incorrect — the labels sit at the level of the switch braces
public static string Describe(OrderStatus status)
{
var text = new StringBuilder();
switch (status)
{
case OrderStatus.Pending: // The label is not indented.
text.Append("Waiting");
break;
default: // The label is not indented.
text.Append("Closed");
break;
}
return text.ToString();
}
Why: The labels indent inside the braces the way members indent inside a class, and the statements of a section indent below their label, so each section reads as a block. These are the defaults of the Microsoft formatting options. The braces of a section that needs its own scope stand in the column of its label, so the braces add no level of their own; indenting them one more level makes IDE0055 report the brace line. Switch expressions are laid out by FMT-050.
Scope: switch statements · Enforced: IDE0055 · Config: csharp_indent_switch_labels, csharp_indent_case_contents, csharp_indent_case_contents_when_block · Sources: MS-IDE-CSFMT
Spacing¶
These rules set where a space goes and where it does not.
FMT-030¶
DO put one space after control-flow keywords (if, for, foreach, while, switch, catch), after commas and for-loop semicolons, around binary operators and on both sides of the colon in a base-type list.
✅ Correct
public static decimal GetLargestAmount(IReadOnlyList<OrderLine> lines)
{
decimal largest = 0m;
for (int index = 0; index < lines.Count; index++)
{
largest = Math.Max(largest, lines[index].Amount);
}
return largest;
}
✅ Correct — the colon of a base-type list
namespace Contoso.Orders;
public sealed class OrderTotals : IComparable<OrderTotals>
{
public decimal Total { get; init; }
public int CompareTo(OrderTotals? other) => other is null ? 1 : Total.CompareTo(other.Total);
}
❌ Incorrect — no space after if and no space after a comma
public static decimal GetLarger(decimal left, decimal right)
{
if(left > right) // No space after the if keyword.
{
return left;
}
return Math.Max(left,right); // No space after the comma.
}
Why: A keyword followed by a parenthesis reads as a method call (if(left > right)), and tokens without a space after a comma run together; one space separates the tokens the eye has to tell apart. The IDE and dotnet format apply these spaces automatically.
Scope: Spaces around keywords, commas, for-loop semicolons, inheritance colons and binary operators · Enforced: IDE0055 · Config: csharp_space_after_keywords_in_control_flow_statements, csharp_space_after_comma, csharp_space_before_comma, csharp_space_after_semicolon_in_for_statement, csharp_space_before_semicolon_in_for_statement, csharp_space_after_colon_in_inheritance_clause, csharp_space_before_colon_in_inheritance_clause · Sources: MS-IDE-CSFMT, RT-EC, ROSLYN, AV
FMT-031¶
DO NOT put a space inside parentheses or square brackets, after a cast, before or after a ., or between a method name and its opening parenthesis in a declaration or a call.
✅ Correct
public static int ToCents(decimal amount) => (int)(amount * 100m);
public static int GetFirstLineCents(Order order) => ToCents(order.Lines[0].Amount);
❌ Incorrect — a space inside the parentheses, after the cast and before the parameter list
public static int RoundUp(decimal amount) => (int)Math.Ceiling( amount ); // Spaces inside the parentheses.
public static int Truncate(decimal amount) => (int) amount; // Space after the cast.
public static int ToCents (decimal amount) => (int)(amount * 100m); // Space before the opening parenthesis.
Why: A space before the parenthesis detaches a name from its argument list, and a space after a cast detaches the cast from its operand. Without those spaces a call, a cast and an index each read as one unit.
Scope: Spaces inside parentheses and brackets, after casts and before argument lists · Enforced: IDE0055 · Config: csharp_space_between_parentheses, csharp_space_after_cast, csharp_space_between_method_declaration_name_and_open_parenthesis, csharp_space_between_method_declaration_parameter_list_parentheses, csharp_space_between_method_declaration_empty_parameter_list_parentheses, csharp_space_between_method_call_name_and_opening_parenthesis, csharp_space_between_method_call_parameter_list_parentheses, csharp_space_between_method_call_empty_parameter_list_parentheses, csharp_space_before_open_square_brackets, csharp_space_between_square_brackets, csharp_space_between_empty_square_brackets, csharp_space_after_dot, csharp_space_before_dot · Sources: MS-IDE-CSFMT, RT-EC
FMT-032¶
DO NOT insert extra spaces to line up names, = signs or end-of-line comments across consecutive lines.
✅ Correct
var order = new Order(7, TimeProvider.System.GetUtcNow());
int lineCount = 3;
decimal orderTotal = 9.99m;
order.AddLine(new OrderLine("SKU-1", lineCount, orderTotal));
❌ Incorrect — extra spaces line up the names
var order = new Order(7, TimeProvider.System.GetUtcNow());
int lineCount = 3; // Extra spaces align the names.
decimal orderTotal = 9.99m;
order.AddLine(new OrderLine("SKU-1", lineCount, orderTotal));
Why: Alignment spaces have to be redone on every neighbouring line when one name changes length, so renaming one variable edits lines that did not otherwise change, and the diff shows noise.
Scope: Declarations, assignments and end-of-line comments · Enforced: IDE0055 · Config: csharp_space_around_declaration_statements · Sources: MS-IDE-CSFMT, RS-INDENT
Line length, wrapping and blank lines¶
These rules set the line limit, the way to wrap a long line, and where blank lines go.
FMT-040¶
DO keep every line at or below 120 characters, counting indentation.
✅ Correct
public static Order CreateOrder(int customerId, IReadOnlyList<OrderLine> initialOrderLines,
DateTimeOffset orderCreatedAt)
{
var order = new Order(customerId, orderCreatedAt);
foreach (OrderLine line in initialOrderLines)
{
order.AddLine(line);
}
return order;
}
❌ Incorrect — one statement line longer than 120 characters before its comment
var order = new Order(7, TimeProvider.System.GetUtcNow());
bool canShip = order.Lines.Count > 0 && !order.IsShipped && order.Total <= 10_000m && order.CustomerId > 0 && order.Status is OrderStatus.Paid; // Longer than 120 characters.
Why: No source from the Microsoft documentation to StyleCop states a production limit. The two guides that state one bracket the range at 100 (Google) and 130 (Aviva); 120 sits inside it and is the common IDE wrap guide. No Roslyn rule reports line length, so reviewers check it, and ReSharper applies max_line_length when it reformats. FMT-041 shows how to wrap. dotnet/runtime sets no limit.
Scope: Every line of C# source, including comments and string literals · Enforced: Review only (no analyzer reports line length) · Config: max_line_length · Sources: MS-CONV, AV, GOOG, RS-LINEBREAKS
FMT-041¶
DO wrap a line that is longer than 120 characters before a binary operator or before each . of a chained call; keep an argument or parameter list on one line when the call or declaration fits in 120 characters, and otherwise wrap it after the last item that fits (one item per line after the opening parenthesis is also accepted); wrap an expression body that does not fit before or after =>; indent each continuation line four spaces.
✅ Correct
var order = new Order(7, TimeProvider.System.GetUtcNow());
bool canShip = order.Lines.Count > 0
&& !order.IsShipped
&& order.Total <= 10_000m;
int distinctSkus = order.Lines
.Where(line => line.Quantity > 0)
.Select(line => line.Sku)
.Distinct()
.Count();
Console.WriteLine(canShip);
Console.WriteLine(distinctSkus);
✅ Correct — a call that fits stays on one line
var order = new Order(7, TimeProvider.System.GetUtcNow());
var line = new OrderLine("SKU-1", 2, 9.99m);
order.AddLine(line);
✅ Correct — a long parameter list wrapped after the last parameter that fits
public static Order CreateOrder(int customerId, IReadOnlyList<OrderLine> initialOrderLines,
DateTimeOffset orderCreatedAt)
{
var order = new Order(customerId, orderCreatedAt);
foreach (OrderLine line in initialOrderLines)
{
order.AddLine(line);
}
return order;
}
✅ Accepted — one argument or parameter per line
public static Order CreateOrder(
int customerId,
IReadOnlyList<OrderLine> initialOrderLines,
DateTimeOffset orderCreatedAt)
{
var order = new Order(customerId, orderCreatedAt);
foreach (OrderLine line in initialOrderLines)
{
order.AddLine(line);
}
return order;
}
✅ Correct — => at the end of the declaration line
public static decimal CalculateGrossAmountWithTax(OrderLine orderLine, decimal applicableTaxRate) =>
orderLine.Amount + (orderLine.Amount * applicableTaxRate);
✅ Correct — => at the start of the continuation line
public static decimal CalculateGrossAmountWithTax(OrderLine orderLine, decimal applicableTaxRate)
=> orderLine.Amount + (orderLine.Amount * applicableTaxRate);
❌ Incorrect — the operator ends the line and two calls share a continuation line
var order = new Order(7, TimeProvider.System.GetUtcNow());
bool canShip = order.Lines.Count > 0 && // Operator at the end of the line.
!order.IsShipped;
int distinctSkus = order.Lines
.Where(line => line.Quantity > 0).Select(line => line.Sku) // Two calls on one continuation line.
.Distinct()
.Count();
❌ Incorrect — an argument list that fits on one line is wrapped
var order = new Order(7, TimeProvider.System.GetUtcNow());
var line = new OrderLine( // The call fits in 120 characters.
"SKU-1",
2,
9.99m);
order.AddLine(line);
Why: Fill-style wrapping is preferred for a long argument or parameter list: the first line carries as many items as fit and the continuation line is indented four spaces, so the list reads as one block and takes the fewest lines. One item per line is accepted; it shows in a diff which item changed. A list that fits in 120 characters stays on one line, because a wrap adds height and no information. An operator at the start of a continuation line shows at once how the line joins the previous one; wrapping after an operator hides it at the end of a long line. One call per line shows in a diff which call changed. A chain or a condition that fits may be wrapped for readability or kept on one line (LANG-051). Both positions of => are correct for an expression body that does not fit.
Scope: Lines that exceed the line-length limit, and argument or parameter lists that fit within it · Enforced: Review only (the wrap options run only in the IDE and ReSharper) · Config: dotnet_style_operator_placement_when_wrapping, resharper_csharp_wrap_before_binary_opsign, resharper_csharp_wrap_chained_method_calls, resharper_csharp_wrap_parameters_style, resharper_csharp_wrap_arguments_style, resharper_csharp_wrap_chained_binary_expressions, resharper_csharp_wrap_before_arrow_with_expressions, resharper_csharp_keep_user_linebreaks · Sources: MS-CONV, RS-LINEBREAKS
FMT-042¶
DO put each statement on its own line, including short statements such as i++; or break;.
✅ Correct
var order = new Order(7, TimeProvider.System.GetUtcNow());
int lineCount = order.Lines.Count;
decimal total = order.Total;
Console.WriteLine(lineCount);
Console.WriteLine(total);
❌ Incorrect — two statements on one line
var order = new Order(7, TimeProvider.System.GetUtcNow());
int lineCount = order.Lines.Count; decimal total = order.Total; // Two statements on one line.
Console.WriteLine(lineCount);
Console.WriteLine(total);
Why: A second statement at the end of a line is easy to miss when scanning down the left margin, and a diff reports both statements as one changed line. One statement per line also keeps the rule for braces (FMT-021) free of exceptions.
Scope: Statements in method, accessor and lambda bodies · Enforced: IDE0055 · Config: csharp_preserve_single_line_statements, resharper_csharp_place_simple_embedded_statement_on_same_line, resharper_multiple_statements_on_one_line_highlighting · Sources: MS-CONV, SA, GOOG, MS-IDE-CSFMT
FMT-043¶
DO separate adjacent methods, properties with bodies, constructors and nested types with exactly one blank line, and never put two blank lines in a row anywhere in a file.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderPricing
{
public decimal Total { get; init; }
public decimal Discount { get; init; }
public decimal NetTotal => Total - Discount;
public decimal ApplyTax(decimal rate) => NetTotal + (NetTotal * rate);
}
❌ Incorrect — two blank lines between members
namespace Contoso.Orders;
public sealed class OrderPricing
{
public decimal Total { get; init; } // Two blank lines follow.
public decimal Discount { get; init; }
}
Why: One blank line makes each member a visible unit; a second blank line carries no extra meaning and invites a private convention for what it means. IDE2000 reports the extra blank line in the build, but it is experimental and reports at the first empty line, so the incorrect example marks the line above.
Scope: Blank lines between type members and between statements · Enforced: IDE2000 · Config: dotnet_style_allow_multiple_blank_lines_experimental, resharper_csharp_keep_blank_lines_in_code, resharper_csharp_keep_blank_lines_in_declarations · Sources: MS-CONV, RT-STYLE, SA, MS-IDE
FMT-044¶
DO NOT leave a blank line directly after an opening brace, directly before a closing brace, or between two consecutive closing braces.
✅ Correct
public static void ShipIfPaid(Order order)
{
if (order.Status is OrderStatus.Paid)
{
order.Ship();
}
}
❌ Incorrect — a blank line after an opening brace and between two closing braces
public static void ShipIfPaid(Order order)
{ // A blank line follows this opening brace.
if (order.Status is OrderStatus.Paid)
{
order.Ship();
}
} // Blank line before this closing brace.
Why: The braces already mark where a block starts and ends, so a blank line next to them adds height without separating anything. IDE2002 reports the blank line between consecutive closing braces; the ReSharper inspection IncorrectBlankLinesNearBraces also covers the other two positions.
Scope: Blank lines next to braces · Enforced: IDE2002, ReSharper: IncorrectBlankLinesNearBraces · Config: csharp_style_allow_blank_lines_between_consecutive_braces_experimental, resharper_csharp_remove_blank_lines_near_braces_in_code, resharper_csharp_remove_blank_lines_near_braces_in_declarations, resharper_incorrect_blank_lines_near_braces_highlighting · Sources: MS-IDE, RS-BLANK
FMT-045¶
DO put exactly one blank line after the last using directive and one after the file-scoped namespace declaration.
✅ Correct
using System.Globalization;
namespace Contoso.Orders;
public static class OrderFormatting
{
public static string FormatTotal(Order order) => order.Total.ToString("C", CultureInfo.InvariantCulture);
}
❌ Incorrect — no blank line after the namespace declaration
using System.Globalization;
namespace Contoso.Orders; // No blank line after the namespace declaration.
public static class OrderFormatting
{
public static string FormatTotal(Order order) => order.Total.ToString("C", CultureInfo.InvariantCulture);
}
Why: The blank lines split the file into three parts (directives, namespace, types) that are easy to tell apart. IDE0055 requires the blank line after the namespace declaration; the blank line after the using list is applied by ReSharper only (resharper_csharp_blank_lines_after_using_list).
Scope: The top of every C# file · Enforced: IDE0055 · Config: resharper_csharp_blank_lines_after_using_list, resharper_csharp_blank_lines_after_file_scoped_namespace_directive · Sources: MS-IDE-CSFMT, RS-BLANK
FMT-046¶
DO put one blank line before a return, throw, break, continue, goto or yield break statement, unless it is the first statement in its block or directly follows a label (case, default or a statement label); when comments sit directly above the statement, put the blank line above the comments.
✅ Correct — a blank line before return, and a guard throw that opens its block
public static decimal CalculateTotal(IReadOnlyList<OrderLine> lines)
{
decimal total = lines.Sum(line => line.Amount);
return total;
}
public static void ValidateLines(IReadOnlyList<OrderLine> lines)
{
if (lines.Count == 0)
{
throw new ArgumentException("An order needs at least one line.", nameof(lines));
}
}
✅ Correct — a blank line before break in a loop
public static int FindFirstShippedId(IReadOnlyList<Order> orders)
{
int shippedId = 0;
foreach (Order order in orders)
{
if (order.IsShipped)
{
shippedId = order.Id;
break;
}
}
return shippedId;
}
❌ Incorrect — return directly after a statement
public static decimal CalculateTotal(IReadOnlyList<OrderLine> lines)
{
decimal total = lines.Sum(line => line.Amount);
return total; // No blank line before return.
}
❌ Incorrect — break directly after a statement
public static int FindFirstShippedId(IReadOnlyList<Order> orders)
{
int shippedId = 0;
foreach (Order order in orders)
{
if (order.IsShipped)
{
shippedId = order.Id;
break; // No blank line before break.
}
}
return shippedId;
}
Why: The blank line makes every exit point of a block visible at a glance, because the eye finds the statement that leaves the block without reading the lines above it. The Microsoft documentation, the Roslyn and runtime style files, StyleCop, Aviva and Google are silent on the point, and ReSharper offers the setting without requiring it. The JetBrains documentation does not list which statements the inspection covers (the blank-lines setting page shows return and throw examples), and the build cannot check it, so it is a review item.
Exceptions:
- The statement is the first statement in its block (a guard
throw, orcontinueinside anif) or directly follows acaseordefaultlabel. - A statement directly after a statement label (for example
ScanDone:) needs no blank line. - Comments directly above the statement stay attached to it; the blank line goes above the comments.
- A preprocessor directive (
#pragma warning restore,#endif) is not a comment: the blank line goes directly above the statement, below the directive. - A throw expression (
?? throw …) and an expression-bodied member are not statements.
Scope: return, throw, break, continue, goto and yield break statements inside blocks (throw expressions such as ?? throw and expression-bodied members are not statements) · Enforced: ReSharper: SeparateControlTransferStatement · Config: resharper_csharp_blank_lines_before_control_transfer_statements, resharper_separate_control_transfer_statement_highlighting · Sources: RS-BLANK, RS-INSPECT
Initializers and parentheses¶
These rules cover multi-line initializers, parentheses in expressions and trailing commas.
FMT-050¶
DO put each member assignment of a multi-line object initializer or anonymous type, and each arm of a multi-line switch expression, on its own line.
✅ Correct
public static Customer CreateCustomer() => new()
{
Id = 7,
Name = "Avery Example"
};
✅ Correct — switch expression
public static string GetLabel(OrderStatus status) => status switch
{
OrderStatus.Pending => "Pending",
OrderStatus.Paid => "Paid",
OrderStatus.Shipped => "Shipped",
OrderStatus.Cancelled => "Cancelled",
_ => throw new ArgumentOutOfRangeException(nameof(status))
};
❌ Incorrect — two members on one line of a multi-line initializer
public static Customer CreateCustomer() => new()
{
Id = 7, Name = "Avery Example" // Two members on one line.
};
Why: One member per line lets a diff show one changed member per changed line and lets a reviewer read the members as a list. The same holds for the arms of a switch expression. A list that fits on one line stays on one line; the rule applies once the list spans lines. There is no comma after the last member (FMT-052).
Scope: Multi-line object initializers, anonymous-type creations and switch expressions · Enforced: IDE0055 · Config: csharp_new_line_before_members_in_object_initializers, csharp_new_line_before_members_in_anonymous_types · Sources: MS-IDE-CSFMT, AV
FMT-051¶
CONSIDER add parentheses where an expression mixes arithmetic, relational or logical operators of different precedence (a + (b * c)), and remove parentheses that clarify nothing.
✅ Correct
public static decimal CalculateTotal(OrderLine line, decimal taxRate) => line.Amount + (line.Amount * taxRate);
❌ Incorrect — mixed precedence without parentheses, and parentheses that clarify nothing
public static decimal CalculateGross(OrderLine line, decimal rate) =>
line.Amount + line.Amount * rate; // Mixed precedence without parentheses.
public static int Count(Order order) => (order.Lines).Count; // Unnecessary parentheses.
Why: Parentheses around the multiplication show the grouping without making the reader recall the precedence table, while parentheses around a single member access ((order.Lines).Count) add tokens and no meaning. IDE0047 and IDE0048 report at suggestion level, so they show in the editor and never fail the build.
Scope: Arithmetic, relational, logical and other binary expressions · Enforced: IDE0047, IDE0048 · Config: dotnet_style_parentheses_in_arithmetic_binary_operators, dotnet_style_parentheses_in_relational_binary_operators, dotnet_style_parentheses_in_other_binary_operators, dotnet_style_parentheses_in_other_operators, resharper_csharp_parentheses_redundancy_style · Sources: MS-CONV, MS-IDE, AV
FMT-052¶
DO NOT put a comma after the last element of an object or collection initializer, collection expression, enum or switch expression.
✅ Correct
namespace Contoso.Orders;
public enum OrderPriority
{
Low = 0,
Normal = 1,
High = 2
}
❌ Incorrect — a comma after the last enum member (reported by ReSharper only)
namespace Contoso.Orders;
public enum OrderPriority
{
Low = 0,
Normal = 1,
High = 2, // Trailing comma after the last member.
}
Why: The JetBrains documentation treats a trailing comma as redundant and removes it by default, while the Microsoft, Roslyn and runtime sources take no position. The rule matches the JetBrains default. The cost is that a diff adding an item also touches the previous line. The build cannot check this rule because Roslyn has no trailing-comma diagnostic; only ReSharper reports it. StyleCop Analyzers rule SA1413 requires trailing commas on multi-line lists.
Scope: Multi-line and single-line initializers, collection expressions, enums and switch expressions · Enforced: ReSharper: ArrangeTrailingCommaInMultilineLists · Config: resharper_csharp_trailing_comma_in_multiline_lists, resharper_csharp_trailing_comma_in_singleline_lists, resharper_arrange_trailing_comma_in_multiline_lists_highlighting · Sources: RS-TRAILING, SA, RT-GC
Files, namespaces and using directives¶
These rules cover the namespace declaration, using directives, file contents and file names, and #region.
FMT-060¶
DO declare the namespace of a file with a file-scoped declaration (namespace Contoso.Orders;), not with a braced namespace block.
✅ Correct — a file-scoped namespace
namespace Contoso.Orders;
public sealed class OrderArchive
{
private readonly List<Order> _orders = [];
public int Count => _orders.Count;
public void Add(Order order) => _orders.Add(order);
}
❌ Incorrect — a braced namespace block
namespace Contoso.Orders // Braced namespace block instead of a file-scoped declaration.
{
public sealed class OrderArchive
{
private readonly List<Order> _orders = [];
public int Count => _orders.Count;
public void Add(Order order) => _orders.Add(order);
}
}
Why: A file declares one top-level type (FMT-064), so it never needs a second namespace, and the IDE converts a braced block to a file-scoped namespace in one action. A braced block compiles to the same program, but it adds one indentation level to every line of the file and offers a second way to write the same declaration, so one form is used everywhere. IDE0161 reports a braced block as a warning, and a warning fails the build.
Scope: Every C# file that declares a namespace · Enforced: IDE0161, ReSharper: ArrangeNamespaceBody · Config: csharp_style_namespace_declarations, resharper_csharp_namespace_body, resharper_arrange_namespace_body_highlighting · Sources: MS-CONV, MS-IDE, RS-FSNS, MS-LANG-12
FMT-061¶
DO place every using directive at the top of the file, before the namespace declaration and outside any namespace.
✅ Correct
using System.Globalization;
namespace Contoso.Orders;
public static class OrderNumbers
{
public static string Format(int orderId) => orderId.ToString("D6", CultureInfo.InvariantCulture);
}
❌ Incorrect — a using directive after the namespace declaration
namespace Contoso.Orders;
using System.Globalization; // Using directive inside the namespace.
public static class OrderNumbers
{
public static string Format(int orderId) => orderId.ToString("D6", CultureInfo.InvariantCulture);
}
Why: All dependencies of a file appear in one place at the top. A directive inside a namespace is resolved relative to that namespace, so the same directive can bind to a different type than it does outside. The examples import System.Globalization, which implicit usings do not supply. The StyleCop default places directives inside the namespace.
Scope: using directives, including aliases and using static · Enforced: IDE0065 · Config: csharp_using_directive_placement, resharper_csharp_add_imports_to_deepest_scope, resharper_csharp_qualified_using_at_nested_scope · Sources: MS-CONV, MS-IDE, RT-STYLE, SA
FMT-062¶
DO order using directives either with System namespaces first and the rest alphabetically, or all alphabetically, with no blank lines between groups, followed by using aliases and then all using static directives at the end, each group in alphabetical order.
✅ Correct — System namespaces first
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging;
using OrderMap = System.Collections.Generic.Dictionary<int, Contoso.Orders.Order>;
using static System.Math;
namespace Contoso.Orders;
public static class OrderReport
{
public static string Describe(OrderMap orders, StringBuilder text, LogLevel level) =>
text.Append(level).Append(Max(orders.Count, 1).ToString(CultureInfo.InvariantCulture)).ToString();
}
✅ Correct — all namespaces in alphabetical order
using Microsoft.Extensions.Logging;
using System.Globalization;
using System.Text;
using OrderMap = System.Collections.Generic.Dictionary<int, Contoso.Orders.Order>;
using static System.Math;
namespace Contoso.Orders;
public static class OrderReport
{
public static string Describe(OrderMap orders, StringBuilder text, LogLevel level) =>
text.Append(level).Append(Max(orders.Count, 1).ToString(CultureInfo.InvariantCulture)).ToString();
}
❌ Incorrect — a blank line splits the list
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging; // A blank line separates two groups.
using OrderMap = System.Collections.Generic.Dictionary<int, Contoso.Orders.Order>;
using static System.Math;
namespace Contoso.Orders;
public static class OrderReport
{
public static string Describe(OrderMap orders, StringBuilder text, LogLevel level) =>
text.Append(level).Append(Max(orders.Count, 1).ToString(CultureInfo.InvariantCulture)).ToString();
}
❌ Incorrect — a using static directive before an alias
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging;
using static System.Math; // The using static directive comes before the alias.
using OrderMap = System.Collections.Generic.Dictionary<int, Contoso.Orders.Order>;
namespace Contoso.Orders;
public static class OrderReport
{
public static string Describe(OrderMap orders, StringBuilder text, LogLevel level) =>
text.Append(level).Append(Max(orders.Count, 1).ToString(CultureInfo.InvariantCulture)).ToString();
}
Why: A fixed order lets a reader find a namespace in the list without reading all of it, and one list without blank lines has one place to insert a new directive. The IDE command that sorts usings and dotnet format move using static directives before aliases, so they are not used to sort the using list; no tool checks the order. The Aviva guide separates groups of different root namespaces with blank lines.
Scope: Order of using directives · Enforced: Review only (no tool checks the order) · Config: dotnet_sort_system_directives_first, dotnet_separate_import_directive_groups, resharper_csharp_sort_usings_with_system_first · Sources: MS-IDE-NETFMT, RT-STYLE, ROSLYN, AV
FMT-063¶
DO delete every using directive the file does not need, including directives for namespaces that implicit global usings already import (System, System.Linq, System.Threading.Tasks and the others), and declare global using directives only in one GlobalUsings.cs per project or as <Using> items in the project file.
✅ Correct
using System.Text;
namespace Contoso.Orders;
public static class OrderLabels
{
public static string Describe(Order order) => new StringBuilder("Order ").Append(order.Status).ToString();
}
❌ Incorrect — a directive that implicit usings already supply
using System.Linq; // Already imported by implicit usings.
using System.Text;
namespace Contoso.Orders;
public static class OrderLabels
{
public static string Describe(Order order) => new StringBuilder("Order ").Append(order.Status).ToString();
}
❌ Incorrect — a global using in a feature file
global using System.Text; // A global using in a feature file.
namespace Contoso.Orders;
public static class OrderLabels
{
public static string Describe(Order order) => new StringBuilder("Order ").Append(order.Status).ToString();
}
Why: An unused directive suggests a dependency the file does not have and hides the ones it does. IDE0005 reports it in the build only when the project generates the XML documentation file (DOC-023); without that setting the rule silently stops running. A global using changes the imports of every file in the project, so it belongs in one place: a GlobalUsings.cs file (for example global using System.Globalization;) or <Using Include="System.Globalization" /> in the project file. A global using in a feature file hides that effect. No tool reports the second case.
Scope: using directives (needs GenerateDocumentationFile=true for the build to report it) · Enforced: IDE0005, ReSharper: RedundantUsingDirective · Config: resharper_redundant_using_directive_highlighting · Sources: MS-IDE, MS-CONV, RS-INSPECT
FMT-064¶
DO declare exactly one top-level type in each file; nested types and file-local helper types stay with the type that uses them.
✅ Correct
Orders/
Order.cs
OrderLine.cs
OrderStatus.cs
❌ Incorrect — three top-level types in one file
Orders/
OrderTypes.cs // Holds Order, OrderLine and OrderStatus: three top-level types in one file.
Why: A reader and a code search find a type by its file name, and one file per type keeps the history of each type separate. Nested and file-local helper types are part of the type that uses them, so they move with it.
Exceptions:
- A generic type and a non-generic type of the same name share one file (NAM-033).
Scope: Top-level types: classes, records, structs, interfaces, enums and delegates · Enforced: Manual · Sources: SA, AV, GOOG
FMT-065¶
DO name each source file exactly after the single top-level type it contains, with the same casing (OrderService.cs for OrderService); generic types and partial types follow NAM-033 and NAM-034.
✅ Correct
Orders/
OrderService.cs // Contains: public sealed partial class OrderService
❌ Incorrect — a file named after a folder and a file with different casing
Orders/
Services.cs // Named after a folder, not after the type OrderService.
orderservice.cs // The casing differs from the type OrderService.
Why: The file name is the first thing a reader sees in a tree or a search result, so it has to name the type. Casing matters because file systems differ in whether orderservice.cs and OrderService.cs are the same file. The names of the files of generic types (NAM-033) and of partial types (NAM-034) are set on page 02 and are not repeated here.
Scope: Source file names · Enforced: Manual · Sources: SA, AV, GOOG
FMT-066¶
DO NOT use #region and #endregion in hand-written code; split a type that needs regions into smaller types or partial files instead.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderBreakdown
{
public decimal Net { get; init; }
public decimal Tax { get; init; }
public decimal Gross => Net + Tax;
}
❌ Incorrect — a region around members
namespace Contoso.Orders;
public sealed class OrderBreakdown
{
#region Properties // Opens a region around members.
public decimal Net { get; init; }
public decimal Tax { get; init; }
#endregion // Closes the region around members.
}
Why: A region hides code in the editor without changing the structure of the type, and a type that needs regions to stay navigable has more than one responsibility. Tools tolerate regions, but no source recommends them.
Exceptions:
- Generated code, which tools may emit with regions.
Scope: Preprocessor regions in hand-written code · Enforced: Manual · Sources: SA, AV, RS-INSPECT
Related¶
- DOC-010: how to write the comments that these layout rules leave out.
- DOC-023: the XML documentation file that makes FMT-063 run in the build.
- TYPE-010, TYPE-011, TYPE-012 and TYPE-013: member order and modifier order.
- LANG-010 and VAR-524: when a member uses an expression body.
- NAM-033 and NAM-034: the file names of generic types and of partial types.
- TOOL-015: the
dotnet formatCI steps, which check formatting and style but not using order. - TOOL-010 and TOOL-014: copy the shipped
.editorconfiginto a repository and enable the build settings that makeIDE0055fail the build.
Sources¶
AV · GOOG · MS-CONV · MS-DOCS-EC · MS-IDE · MS-IDE-CSFMT · MS-IDE-NETFMT · MS-LANG-12 · ROSLYN · RS-BLANK · RS-BRACES · RS-BRACES-STYLE · RS-FSNS · RS-INDENT · RS-INSPECT · RS-LINEBREAKS · RS-TRAILING · RT-EC · RT-GC · RT-STYLE · SA
Previous: Home · Home · Next: Naming Cheat Sheet and Principles