Language Features¶
Rule prefix: LANG · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
Home · Rule index · Naming cheat sheet
This chapter covers which C# language construct to use for a given job: expression bodies, primary constructors and local functions, pattern matching and null handling, initializers, nameof, string building, comparison and culture, LINQ layout, and the C# 12 to 14 features (extension blocks, null-conditional assignment, unbound generics in nameof). The examples are application code in the Contoso.Orders domain.
Naming rules are on page 02, page 03 and page 04. Declarations of variables, fields, properties and collections are on page 05 and page 06. Types, members and modifiers are on page 08, exceptions and guard clauses on page 10, and async code on page 11.
The table maps a job to the construct this chapter prescribes. A rule marked Manual in its metadata line is checked in review, not by a tool (manual rule).
| You want to | Write | Rule |
|---|---|---|
| Return one value from a method in one line | public static decimal GetTotal(Order order) => order.Total; |
LANG-010 |
| Capture constructor parameters | public sealed class Checker(TimeProvider timeProvider) |
LANG-012 |
| Test a type and use the result | if (payment is CardPayment card) |
LANG-020 |
| Map every enum member to a value | status switch with one arm per member and _ last |
LANG-021 |
Fall back when a value is null |
customer.Email ?? customer.Name |
LANG-022 |
| Compare identifiers, keys and roles | string.Equals(a, b, StringComparison.Ordinal) |
LANG-041 |
| Format a number for a file or a log | total.ToString("F2", CultureInfo.InvariantCulture) |
LANG-043 |
| Filter and project a sequence | orders.Where(order => order.IsShipped).Select(order => order.Id) |
LANG-050 |
Rule index¶
| ID | Level | Rule | Enforced |
|---|---|---|---|
| LANG-010 | CONSIDER | an expression body (=>) for a method, operator, local function, lambda or constructor whose body is a single expression that fits within the line limit, wrapped at => if needed, and use a block body for anything longer. |
IDE0022, IDE0023, IDE0024, IDE0061, IDE0053, IDE0021, ReSharper: ArrangeMethodOrOperatorBody, ArrangeConstructorOrDestructorBody |
| LANG-012 | DO | declare a primary constructor for a class or struct whose constructor only stores its parameters, reference the parameters directly in members, and never assign to a primary-constructor parameter. | IDE0290, ReSharper: ConvertToPrimaryConstructor |
| LANG-013 | DO | declare a local function instead of storing a lambda or anonymous method in a local variable. | IDE0039 |
| LANG-014 | DO | mark a local function static when it uses no local variable, parameter or instance member of the enclosing method. |
IDE0062 |
| LANG-020 | DO | test and convert a value in one step with a declaration pattern (if (payment is CardPayment card)) instead of as followed by a null check or is followed by a cast. |
IDE0019, IDE0020, IDE0260, ReSharper: MergeIntoPattern |
| LANG-021 | DO | write a switch expression instead of a switch statement when every case returns or assigns a value, and handle every enum member or end with a discard arm _. |
IDE0066, IDE0072, ReSharper: ConvertSwitchStatementToSwitchExpression |
| LANG-022 | DO | handle null with ??, ??=, ?. and is null or is not null instead of an explicit null-check branch, a conditional operator around != null or ReferenceEquals(x, null). |
IDE0029, IDE0030, IDE0031, IDE0041, IDE0074, IDE0150, IDE0270, IDE1005 |
| LANG-023 | CONSIDER | the conditional operator (a ? b : c) to assign or return one of two values, and never nest one conditional operator inside another. |
IDE0045, IDE0046 |
| LANG-030 | DO | set members in an object or collection initializer when you create the object, instead of assigning them in separate statements afterwards. | IDE0017, ReSharper: UseObjectOrCollectionInitializer |
| LANG-031 | DO | write nameof(x) instead of a string literal or typeof(T).Name wherever the text names a parameter, member or type. |
CA1507, IDE0082, ReSharper: UseNameofExpression |
| LANG-032 | CONSIDER | a throw expression inside ?? or ?: (_carrier = carrier ?? throw new InvalidOperationException(...)) instead of a separate check-and-throw statement before an assignment; for argument null checks use ArgumentNullException.ThrowIfNull (ERR-014). |
IDE0016 |
| LANG-033 | DO | write compound assignments (total += line.Amount, count ??= 0) instead of repeating the variable, and use ++ and -- only as standalone statements, never inside a larger expression. |
IDE0054 |
| LANG-034 | DO | write an unbound generic type in nameof (nameof(List<>)) instead of a placeholder type argument (nameof(List<int>)). |
IDE0340 |
| LANG-035 | DO | let the compiler infer the name of an anonymous-type member and of a tuple element: write new { order.Total } and (order.Id, order.Total), not new { Total = order.Total } and (Id: order.Id, Total: order.Total). |
IDE0037 |
| LANG-040 | DO | build a string from a few parts with interpolation, from a sequence with string.Join or string.Concat, and in a loop with a StringBuilder, never with += on a string inside a loop. |
Manual |
| LANG-041 | DO | pass an explicit StringComparison to every string comparison, prefix test, search and Equals call, using Ordinal or OrdinalIgnoreCase for identifiers, keys, paths, roles and other non-linguistic values. |
CA1309, CA1310, CA1307, CA1862, CA2251 |
| LANG-042 | DO | test for missing text with string.IsNullOrEmpty or, when whitespace counts as missing, string.IsNullOrWhiteSpace, instead of comparing with null, "" or Length == 0. |
CA1820, ReSharper: ReplaceWithStringIsNullOrEmpty |
| LANG-043 | DO | pass CultureInfo.InvariantCulture when formatting or parsing values that machines read (files, logs, protocols, keys) and CultureInfo.CurrentCulture for text shown to users, and never rely on the implicit current culture; parse untrusted text with TryParse. |
CA1305 |
| LANG-044 | DO | normalize case with ToUpperInvariant or ToLowerInvariant, or better compare with StringComparison.OrdinalIgnoreCase, instead of calling culture-sensitive ToUpper or ToLower. |
CA1304, CA1311 |
| LANG-050 | DO | write LINQ queries in method syntax (orders.Where(...).Select(...)) and use query syntax only for joins, let clauses or several from clauses. |
Manual |
| LANG-051 | DO | when a LINQ method chain does not fit on one line, put each call on its own line starting with ., and put each clause of a multi-line query expression on its own line. |
IDE0055 |
| LANG-052 | DO | materialize a query with ToList or ToArray before enumerating it more than once, and test whether a sequence has elements with Any() or, on a materialized collection, with Count or Length, never with Count() > 0. |
CA1827, CA1829, CA1860, CA1851, ReSharper: PossibleMultipleEnumeration |
| LANG-060 | DO | declare new extension members in C# 14 extension(...) blocks inside the extension class that NAM-127 names, and add an extension only for a type you cannot change. |
Manual |
| LANG-061 | AVOID | goto and statement labels; write a loop, an early return or a local function instead. |
Manual |
| LANG-062 | DO | write the entry point of an application as top-level statements in Program.cs, and never use top-level statements in libraries or in any other file. |
IDE0210 |
| LANG-063 | DO | write a null-conditional assignment (customer?.Email = email;) instead of an if (customer is not null) block around a single assignment. |
Manual |
| LANG-064 | DO | use a checked expression or block wherever an integer overflow must throw instead of wrapping (sizes, money in minor units, counters used for allocation). |
Manual |
Expression bodies, constructors and local functions¶
These rules cover how a member body is written: an expression body for single-expression methods and constructors, a block body when a body needs more, a primary constructor when a constructor only stores its parameters, and local functions instead of stored lambdas. Properties are on page 06 (VAR-524).
LANG-010¶
CONSIDER an expression body (=>) for a method, operator, local function, lambda or constructor whose body is a single expression that fits within the line limit, wrapped at => if needed, and use a block body for anything longer.
✅ Correct
public static decimal CalculateTotal(IReadOnlyList<OrderLine> lines) => lines.Sum(line => line.Amount); // one line
public static decimal CalculateRoundedTotal(Order order)
{
return Round(order.Total);
static decimal Round(decimal amount) => Math.Round(amount, 2); // local function, one expression
}
✅ Correct — a block body once the body needs more than one statement
public static string Summarize(Order order)
{
int unitCount = 0;
decimal total = 0m;
foreach (OrderLine line in order.Lines)
{
unitCount += line.Quantity;
total += line.Amount;
}
return $"{unitCount} units, {total:N2}";
}
✅ Correct — a constructor with one computed assignment as an expression body, and a block body once it validates its arguments
namespace Contoso.Orders;
public sealed class OrderBatch
{
private readonly int _size;
public OrderBatch(int size) => _size = size * 2; // one computed assignment, not a plain copy of the parameter
public OrderBatch() => _size = 20; // a second constructor, so a primary constructor does not fit
public bool IsFull(int count) => count >= _size;
}
public sealed class OrderLimit
{
private readonly int _size;
public OrderLimit(int size)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(size); // validation needs a block body
_size = size;
}
public bool IsFull(int count) => count >= _size;
}
❌ Incorrect — a block body that only returns one expression
public static decimal CalculateTotal(IReadOnlyList<OrderLine> lines) // one-expression block body
{
return lines.Sum(line => line.Amount);
}
public static decimal CalculateRoundedTotal(Order order)
{
return Round(order.Total);
static decimal Round(decimal amount) // one-expression block body
{
return Math.Round(amount, 2);
}
}
❌ Incorrect — a constructor block body that only makes one assignment
namespace Contoso.Orders;
public sealed class OrderBatch
{
private readonly int _size;
public OrderBatch(int size) // one-expression block body
{
_size = size * 2;
}
public OrderBatch() => _size = 20;
public bool IsFull(int count) => count >= _size;
}
Why: An expression body keeps the signature and the result together, so the reader sees both at once. A body that needs a second statement, or a line break inside the expression itself (not the break at =>), reads better as a block because each statement stays on its own line. A constructor is where a type checks its arguments, so a constructor with a guard clause or more than one statement keeps a block body. A constructor that makes one assignment or one call has nothing to add to a block, so the shipped configuration sets csharp_style_expression_bodied_constructors to when_on_single_line and IDE0021 suggests the expression body. A constructor that only copies its parameters into fields is neither case: write a primary constructor (LANG-012). IDE0290 reports such a constructor when it is the only constructor of the class, expression-bodied or not, so the examples give the class a second constructor, which keeps IDE0290 silent. The rule is a CONSIDER because the sources split: the dotnet/docs configuration allows => on every member kind, while the Roslyn repository disallows it on methods.
Exceptions:
- An expression that does not fit within the 120-character line limit (FMT-040) even after wrapping at
=>(FMT-041) stays in a block body. - A constructor with a guard clause or more than one statement keeps a block body.
Scope: Methods, operators, local functions, lambdas and constructors (properties: VAR-524) · Enforced: IDE0022, IDE0023, IDE0024, IDE0061, IDE0053, IDE0021 (suggestion for constructors), ReSharper: ArrangeMethodOrOperatorBody, ArrangeConstructorOrDestructorBody · Config: csharp_style_expression_bodied_methods, csharp_style_expression_bodied_operators, csharp_style_expression_bodied_local_functions, csharp_style_expression_bodied_lambdas, csharp_style_expression_bodied_constructors, resharper_csharp_method_or_operator_body, resharper_csharp_local_function_body, resharper_csharp_constructor_or_destructor_body, resharper_csharp_use_heuristics_for_body_style, resharper_arrange_method_or_operator_body_highlighting, resharper_arrange_local_function_body_highlighting, resharper_arrange_constructor_or_destructor_body_highlighting · Sources: MS-IDE-OPTIONS, RS-BODIES, AV, GOOG, ROSLYN
LANG-011¶
Retired (2026-11-30) — superseded by LANG-010
LANG-012¶
DO declare a primary constructor for a class or struct whose constructor only stores its parameters, reference the parameters directly in members, and never assign to a primary-constructor parameter.
C# 12: Primary constructors on classes and structs need C# 12. With a
LangVersionbelow 12, declare a constructor and copy each parameter into areadonlyfield.
✅ Correct
namespace Contoso.Orders;
public sealed class InvoiceDueChecker(TimeProvider timeProvider)
{
public bool IsOverdue(Invoice invoice) => timeProvider.GetUtcNow() > invoice.DueDate; // parameter read directly
}
❌ Incorrect — the constructor only copies its parameter into a field
namespace Contoso.Orders;
public sealed class InvoiceDueChecker
{
private readonly TimeProvider _timeProvider;
public InvoiceDueChecker(TimeProvider timeProvider) // constructor only stores its parameter
{
_timeProvider = timeProvider;
}
public bool IsOverdue(Invoice invoice) => _timeProvider.GetUtcNow() > invoice.DueDate;
}
❌ Incorrect — a primary-constructor parameter is reassigned
namespace Contoso.Orders;
public sealed class OrderCounter(int start)
{
public int GetNext()
{
start++; // assigns to a primary-constructor parameter
return start;
}
}
Why: The compiler stores a captured primary-constructor parameter in a hidden mutable field. Reading it directly removes the field, the constructor and the assignment that a classic constructor needs. Assigning to the parameter changes that hidden field, so the value is no longer the one the caller passed, and no readonly modifier protects it. The alternatives are a classic constructor that copies parameters into fields, and required properties for injected services.
Exceptions:
- Data types use
requiredandinitproperties, and small immutable data uses a positional record (VAR-522). - A constructor with a guard clause or more than one statement keeps a block body (LANG-010).
Scope: Classes and structs whose constructors only store their parameters · Enforced: IDE0290, ReSharper: ConvertToPrimaryConstructor · Config: csharp_style_prefer_primary_constructors, resharper_convert_to_primary_constructor_highlighting · Sources: MS-CONV, MS-IDE, MS-LANG-12, RT-STYLE, AV
LANG-013¶
DO declare a local function instead of storing a lambda or anonymous method in a local variable.
✅ Correct
private const decimal TaxMultiplier = 1.2m;
public static decimal CalculateTotalWithTax(Order order)
{
return AddTax(order.Total);
static decimal AddTax(decimal amount) => amount * TaxMultiplier; // local function, not a stored lambda
}
❌ Incorrect — a lambda stored in a local variable
private const decimal TaxMultiplier = 1.2m;
public static decimal CalculateTotalWithTax(Order order)
{
Func<decimal, decimal> addTax = amount => amount * TaxMultiplier; // lambda stored in a local
return addTax(order.Total);
}
Why: A local function is declared like a method: it can be generic, can be an iterator (yield), and can be static (LANG-014). A lambda stored in a variable is always converted to a delegate, so it cannot be generic or an iterator, and every call goes through a delegate instance. A local function is a plain method unless you convert it to a delegate. (A lambda can also be static, which VAR-547 prescribes; that is not a difference between the two.)
Exceptions:
- Pass a lambda directly as an argument (
lines.Sum(line => line.Amount)); only a lambda stored in a local variable is covered. - Keep the delegate when the variable is reassigned or added to a collection of delegates.
Scope: Lambdas stored in local variables · Enforced: IDE0039 · Config: csharp_style_prefer_local_over_anonymous_function · Sources: MS-IDE, AV
LANG-014¶
DO mark a local function static when it uses no local variable, parameter or instance member of the enclosing method.
✅ Correct
public static decimal CalculateGrossTotal(Order order, decimal taxRate)
{
return AddTax(order.Total, taxRate);
static decimal AddTax(decimal amount, decimal rate) => amount * (1 + rate); // state arrives as parameters
}
❌ Incorrect — a local function that captures nothing but is not static
private const decimal TaxMultiplier = 1.2m;
public static decimal CalculateGrossTotal(Order order)
{
return AddTax(order.Total);
decimal AddTax(decimal amount) => amount * TaxMultiplier; // captures nothing but is not static
}
Why: The compiler rejects a static local function that reads the enclosing state, so a later edit cannot add a hidden capture. A local function that captures state shares the enclosing method's variables through a closure; the compiler can pass that closure as a struct, but it becomes a heap object once the function is converted to a delegate. static rules a capture out, and passing the values as parameters, as above, keeps the dependencies visible in the signature.
Exceptions:
- A local function that reads or writes a local variable of the enclosing method cannot be
static. Pass the value as a parameter first if the function is a pure calculation.
Scope: Local functions · Enforced: IDE0062 · Config: csharp_prefer_static_local_function · Sources: MS-IDE, RT-EC
Pattern matching and conditional logic¶
These rules cover type tests, switch expressions, null handling and the conditional operator.
LANG-020¶
DO test and convert a value in one step with a declaration pattern (if (payment is CardPayment card)) instead of as followed by a null check or is followed by a cast.
✅ Correct
public static string Describe(Payment payment)
{
if (payment is CardPayment card) // test and convert in one step
{
return card.MaskedNumber;
}
return "Other payment";
}
❌ Incorrect — as with a null check, and is with a cast
public static string Describe(object value)
{
string? text = value as string; // as followed by a null check
if (text != null)
{
return text;
}
if (value is CardPayment)
{
CardPayment card = (CardPayment)value; // cast after an is test
return card.MaskedNumber;
}
return "Other value";
}
Why: The pattern tests the type once, assigns the variable only when the test succeeds, and limits its scope to the branch where it is valid. as leaves a nullable variable in scope after the check, and is followed by a cast tests the type twice.
Exceptions:
- A plain cast
(CardPayment)paymentis correct when the type is certain and a wrong type must throwInvalidCastException.
Scope: Type tests and casts · Enforced: IDE0019, IDE0020, IDE0260, ReSharper: MergeIntoPattern · Config: csharp_style_pattern_matching_over_as_with_null_check, csharp_style_pattern_matching_over_is_with_cast_check, resharper_merge_into_pattern_highlighting · Sources: MS-IDE, AV, MS-CONV
LANG-021¶
DO write a switch expression instead of a switch statement when every case returns or assigns a value, and handle every enum member or end with a discard arm _.
✅ Correct
public static string GetLabel(OrderStatus status)
{
return status switch
{
OrderStatus.Pending => "Pending",
OrderStatus.Paid => "Paid",
OrderStatus.Shipped => "Shipped",
OrderStatus.Cancelled => "Cancelled",
_ => "Unknown" // covers values cast from an int
};
}
❌ Incorrect — a switch statement in which every case returns a value
public static string GetLabel(OrderStatus status)
{
switch (status) // every case returns a value
{
case OrderStatus.Pending:
return "Pending";
case OrderStatus.Paid:
return "Paid";
case OrderStatus.Shipped:
return "Shipped";
default:
return "Unknown";
}
}
Why: A switch expression must produce a value for every input, so the compiler warns about a missing case instead of letting the method fall through. It is also shorter: one arm per case and no return or break. Ending with _ handles an enum value that was cast from an integer and keeps the method total when a member is added.
Exceptions:
- Keep a switch statement when a case runs several statements, awaits, or has a side effect and returns no value.
Scope: switch statements whose cases each produce a value · Enforced: IDE0066, IDE0072, ReSharper: ConvertSwitchStatementToSwitchExpression · Config: csharp_style_prefer_switch_expression, resharper_convert_switch_statement_to_switch_expression_highlighting · Sources: MS-IDE, AV, RT-EC
LANG-022¶
DO handle null with ??, ??=, ?. and is null or is not null instead of an explicit null-check branch, a conditional operator around != null or ReferenceEquals(x, null).
✅ Correct
public static string GetContact(Customer customer) => customer.Email ?? customer.Name; // ?? for a fallback
public static int? GetEmailLength(Customer customer) => customer.Email?.Length; // ?. for an optional member
✅ Correct — ??= and is null
private List<string>? _warnings;
public void AddWarning(string message)
{
_warnings ??= []; // create the list on first use
_warnings.Add(message);
}
public static bool IsMissing(Order? order) => order is null; // is null, not == null
❌ Incorrect — null handling written out
public static string GetContact(Customer customer) =>
customer.Email != null ? customer.Email : customer.Name; // ?? written as ?:
public static int? GetEmailLength(Customer customer) =>
customer.Email != null ? customer.Email.Length : null; // ?. written out
public static bool IsMissing(Order? order) => ReferenceEquals(order, null); // ReferenceEquals instead of is null
Why: Each operator states the intent once. ?? names the fallback, ?. evaluates the receiver once and skips the call, and is null cannot be redirected by an overloaded == operator. The same applies to events and delegates: write Shipped?.Invoke(this, args) instead of copying the delegate and testing it. A negated check reads as is not null, not !(x is null).
Exceptions:
- Use
==or!=when you want a user-defined equality operator to run. None of theContoso.Ordersdomain types overloads it.
Scope: Null checks and null fallbacks · Enforced: IDE0029, IDE0030, IDE0031, IDE0041, IDE0074, IDE0150, IDE0270, IDE1005 · Config: dotnet_style_coalesce_expression, dotnet_style_null_propagation, dotnet_style_prefer_is_null_check_over_reference_equality_method, dotnet_style_prefer_compound_assignment, csharp_style_prefer_null_check_over_type_check, csharp_style_conditional_delegate_call, resharper_csharp_null_checking_pattern_style · Sources: MS-IDE, AV, RT-EC
LANG-023¶
CONSIDER the conditional operator (a ? b : c) to assign or return one of two values, and never nest one conditional operator inside another.
✅ Correct
private const decimal FreeShippingThreshold = 50m;
private const decimal StandardShippingFee = 4.95m;
public static decimal GetShippingFee(Order order) => order.Total >= FreeShippingThreshold ? 0m : StandardShippingFee;
❌ Incorrect — an if/else that only returns, and one that only assigns
private const decimal FreeShippingThreshold = 50m;
private const decimal StandardShippingFee = 4.95m;
private const decimal ExpressSurcharge = 9.99m;
public static decimal GetShippingFee(Order order, bool isExpress)
{
decimal fee;
if (order.Total >= FreeShippingThreshold) // if/else that only assigns
{
fee = 0m;
}
else
{
fee = StandardShippingFee;
}
if (isExpress) // if/else that only returns
{
return fee + ExpressSurcharge;
}
else
{
return fee;
}
}
❌ Incorrect — a conditional operator nested inside another
public static string GetStatusLabel(Order order)
{
string label = order.IsShipped ? "Shipped" : order.Total > 0m ? "Open" : "Empty"; // nested conditional operator
return label;
}
Why: When both branches only return or only assign, the conditional operator says so in one line. Nesting one inside another (a ? b : c ? d : e) forces the reader to track which branch owns which condition; use a switch expression (LANG-021) or an if/else for three or more outcomes. No tool checks nesting, so reviewers do.
Exceptions:
- Keep
if/elsewhen a branch has more than one statement or a side effect.
Scope: Selecting one of two values · Enforced: IDE0045, IDE0046 · Config: dotnet_style_prefer_conditional_expression_over_assignment, dotnet_style_prefer_conditional_expression_over_return · Sources: MS-IDE, AV
Initializers, nameof and operators¶
These rules cover object initializers, nameof, throw expressions, compound assignment and unbound generic types in nameof.
LANG-030¶
DO set members in an object or collection initializer when you create the object, instead of assigning them in separate statements afterwards.
✅ Correct
public static Customer CreateCustomer()
{
return new()
{
Id = 7,
Name = "Avery Example"
};
}
❌ Incorrect — members set after construction
namespace Contoso.Orders;
public sealed class ContactCard
{
public string Name { get; set; } = "";
public static ContactCard Create()
{
var card = new ContactCard(); // members set after construction
card.Name = "Avery Example";
return card;
}
}
Why: The initializer keeps creation and population in one expression, so the object is never visible half-filled, and it is the only way to fill required and init members such as those of Customer. A target-typed new() repeats no type name, and the braces follow the layout of FMT-050 with no trailing comma (FMT-052). The same applies to collections that are filled right after creation: use a collection expression (VAR-531).
Exceptions:
- Assign members afterwards when a value depends on a statement that cannot be an expression, such as a
tryblock or a loop.
Scope: Objects and collections that are populated right after creation · Enforced: IDE0017, ReSharper: UseObjectOrCollectionInitializer · Config: dotnet_style_object_initializer, resharper_use_object_or_collection_initializer_highlighting · Sources: MS-CONV, MS-IDE, AV
LANG-031¶
DO write nameof(x) instead of a string literal or typeof(T).Name wherever the text names a parameter, member or type.
✅ Correct
public static OrderLine CreateLine(string sku, int quantity, decimal unitPrice)
{
if (!sku.StartsWith("SKU-", StringComparison.Ordinal))
{
throw new ArgumentException("A SKU starts with SKU-.", nameof(sku)); // nameof follows renames
}
return new OrderLine(sku, quantity, unitPrice);
}
public static string GetTypeLabel() => nameof(Order); // nameof, not typeof(Order).Name
❌ Incorrect — names written as text
public static OrderLine CreateLine(string sku, int quantity, decimal unitPrice)
{
if (!sku.StartsWith("SKU-", StringComparison.Ordinal))
{
throw new ArgumentException("A SKU starts with SKU-.", "sku"); // parameter name as a string
}
return new OrderLine(sku, quantity, unitPrice);
}
public static string GetTypeLabel() => typeof(Order).Name; // typeof(T).Name
Why: nameof is checked by the compiler. When you rename the parameter or the type, the text follows; a string literal silently goes stale. typeof(T).Name also does work at run time that nameof does at compile time. The example throws ArgumentException for a format check that no helper covers. For null and range checks prefer the throw helpers such as ArgumentNullException.ThrowIfNull(x) and ArgumentOutOfRangeException.ThrowIfNegative(x), which capture the argument name for you (ERR-014).
Exceptions:
- Keep a literal when the text is a contract that must not change with a rename, such as a serialized property name or a log field name.
Scope: Names of parameters, members and types written as text · Enforced: CA1507, IDE0082, ReSharper: UseNameofExpression · Config: resharper_use_nameof_expression_highlighting · Sources: RT-STYLE, MS-IDE, MS-CA
LANG-032¶
CONSIDER a throw expression inside ?? or ?: (_carrier = carrier ?? throw new InvalidOperationException(...)) instead of a separate check-and-throw statement before an assignment; for argument null checks use ArgumentNullException.ThrowIfNull (ERR-014).
✅ Correct
namespace Contoso.Orders;
public sealed record Shipment(int OrderId, string? Carrier)
{
public string RequireCarrier()
{
return Carrier ?? throw new InvalidOperationException("The shipment has no carrier set."); // throw expression
}
}
❌ Incorrect — a separate check before the value is used
namespace Contoso.Orders;
public sealed record Shipment(int OrderId, string? Carrier)
{
public string RequireCarrier()
{
if (Carrier is null) // separate check before use
{
throw new InvalidOperationException("The shipment has no carrier set.");
}
return Carrier;
}
}
Why: The throw expression joins the check and the use, so the value cannot be used before it is checked. The tool defers to the throw helpers for method arguments: for those, write ArgumentNullException.ThrowIfNull(shipment) (ERR-014). The throw expression is for state that is not an argument, such as a lookup result or a configured value, where InvalidOperationException is the right type. IDE0016 reports a null check followed by an assignment; it does not report a check followed by a return, as in the incorrect example, so no build diagnostic fires there and the example is a review item.
Exceptions:
- Keep the separate statement when the failure path needs more than one statement, such as logging before the throw.
Scope: Assignments guarded by a check that throws · Enforced: IDE0016 · Config: csharp_style_throw_expression · Sources: MS-IDE, RT-EC
LANG-033¶
DO write compound assignments (total += line.Amount, count ??= 0) instead of repeating the variable, and use ++ and -- only as standalone statements, never inside a larger expression.
✅ Correct
public static string Tally(Order order)
{
decimal total = 0m;
int lineCount = 0;
foreach (OrderLine line in order.Lines)
{
total += line.Amount; // compound assignment
lineCount++; // ++ on its own line
}
return $"{lineCount} lines, {total:N2}";
}
❌ Incorrect — the variable is repeated
public static decimal Tally(Order order)
{
decimal total = 0m;
foreach (OrderLine line in order.Lines)
{
total = total + line.Amount; // repeated variable
}
return total;
}
❌ Incorrect — ++ inside a larger expression
public static decimal SumFirstTwo(IReadOnlyList<OrderLine> lines)
{
int index = 0;
decimal total = lines[index++].Amount + lines[index++].Amount; // ++ inside a larger expression
return total;
}
Why: total += x names the variable once, so a typo cannot make the two sides differ. An increment inside a larger expression, such as items[index++], hides a side effect in the middle of a read; put index++; on its own line after the use.
Exceptions:
- None.
Scope: Updates of a variable from its own value · Enforced: IDE0054 · Config: dotnet_style_prefer_compound_assignment · Sources: MS-IDE, RT-GC
LANG-034¶
DO write an unbound generic type in nameof (nameof(List<>)) instead of a placeholder type argument (nameof(List<int>)).
C# 14: Unbound generic types in
nameofneed C# 14. With aLangVersionbelow 14,nameof(List<>)does not compile; write a type argument such asnameof(List<int>).
✅ Correct
public static string GetRepositoryLabel() => nameof(Dictionary<,>); // unbound generic type
❌ Incorrect — dummy type arguments
public static string GetRepositoryLabel() => nameof(Dictionary<int, Order>); // dummy type arguments in nameof
Why: nameof returns only the type name, so the type arguments carry no information. A made-up argument such as int suggests a meaning the result does not have and forces a reader to check whether the argument matters.
Exceptions:
- None.
Scope: nameof of generic types · Enforced: IDE0340 · Config: csharp_style_prefer_unbound_generic_type_in_nameof · Sources: MS-LANG-14, MS-IDE
LANG-035¶
DO let the compiler infer the name of an anonymous-type member and of a tuple element: write new { order.Total } and (order.Id, order.Total), not new { Total = order.Total } and (Id: order.Id, Total: order.Total).
✅ Correct
public static string Describe(Order order)
{
var summary = new { order.Total }; // member named Total
return $"Total: {summary.Total:N2}";
}
public static (int Id, decimal Total) Snapshot(Order order) => (order.Id, order.Total); // elements named Id and Total
❌ Incorrect — names that repeat the name the compiler infers
public static string Describe(Order order)
{
var summary = new { Total = order.Total }; // member name repeats the property name
return $"Total: {summary.Total:N2}";
}
public static (int Id, decimal Total) Snapshot(Order order) => (Id: order.Id, Total: order.Total); // element names repeat the property names
Why: When a member or element is initialized from a property or a field, the compiler gives it the name of that property or field, so Total = order.Total states the same name twice. A repeated name adds tokens and can drift when one side is renamed. The same-name test is case-sensitive: total = order.Total names a member total, not the Total that the compiler would infer, so the explicit name stays. IDE0037 reports a name that repeats the inferred one; the shipped configuration sets both options to true and the rule to warning.
Exceptions:
- Keep the name when it differs from the inferred one, which includes a different case (NAM-240 names anonymous-type members in PascalCase).
- Keep the name when the initializer has no name to infer, such as a method call or an arithmetic expression (
Total = order.Total * 2).
Scope: Anonymous-type creation expressions and tuple expressions · Enforced: IDE0037 · Config: dotnet_style_prefer_inferred_anonymous_type_member_names, dotnet_style_prefer_inferred_tuple_names · Sources: MS-IDE-LANG, MS-IDE-OPTIONS, MS-IDE
Strings and comparisons¶
These rules cover building strings, comparing them, testing for missing text, formatting with a culture and changing case. The comparison and culture rules matter for correctness and security: a culture-sensitive comparison in an authorization check changes the result with the machine's culture. Secrets and tokens are compared in constant time (SEC-012).
LANG-040¶
DO build a string from a few parts with interpolation, from a sequence with string.Join or string.Concat, and in a loop with a StringBuilder, never with += on a string inside a loop.
✅ Correct
public static string FormatTitle(Order order) => $"Order {order.Id}: {order.Lines.Count} lines"; // a few parts
public static string JoinSkus(Order order) => string.Join(", ", order.Lines.Select(line => line.Sku)); // a sequence
public static string BuildReport(Order order)
{
var report = new StringBuilder();
foreach (OrderLine line in order.Lines)
{
report.AppendLine(line.Sku); // appending in a loop
}
return report.ToString();
}
❌ Incorrect — concatenation with += in a loop
public static string BuildSkuText(Order order)
{
string text = "";
foreach (OrderLine line in order.Lines)
{
text += line.Sku + ", "; // string concatenation in a loop
}
return text;
}
Why: A string is immutable, so each += allocates a new string and copies the old one; a loop over n items copies n times. string.Join and StringBuilder allocate once or grow a buffer. Interpolation reads as the final text. Log messages use constant templates, not interpolation (SEC-073).
Exceptions:
- None.
Scope: Building strings from several parts · Enforced: Manual · Sources: MS-CONV, AV, GOOG
LANG-041¶
DO pass an explicit StringComparison to every string comparison, prefix test, search and Equals call, using Ordinal or OrdinalIgnoreCase for identifiers, keys, paths, roles and other non-linguistic values.
✅ Correct
public static bool IsAdministrator(string role) => string.Equals(role, "Administrator", StringComparison.Ordinal);
public static bool IsKnownSku(string sku) => sku.StartsWith("SKU-", StringComparison.Ordinal); // ordinal: no culture rules
public static bool IsRush(string note) => note.Contains("rush", StringComparison.OrdinalIgnoreCase); // the comparison is stated
❌ Incorrect — the comparison uses the current culture — Insecure, do not use
// INSECURE: culture rules can change the result of this authorization check
public static bool IsAdministrator(string role) =>
string.Compare(role, "Administrator") == 0; // culture-sensitive comparison in an authorization check
❌ Incorrect — a string method called without a StringComparison
public static bool IsRush(string note) => note.Contains("rush"); // no StringComparison argument
Why: Without an argument, StartsWith(string) and similar calls use the current culture, which applies linguistic rules: it can ignore some characters and treat different character sequences as equal, and the result depends on the machine's culture settings. For an identifier, key, path or role that is a different answer on a different server, and in an authorization check it is a security defect. Ordinal comparison compares the UTF-16 code units, which is what a protocol value needs. The explicit argument also shows the reader that the choice was made. The build reports the two causes separately. CA1310 reports a culture-sensitive comparison of strings, such as StartsWith(string) or IndexOf(string), and CA1309 reports a comparison that should be ordinal. CA1307 reports any call to an overload without a StringComparison parameter when a twin that has one exists, including calls that are already ordinal, such as Contains(string), Contains(char) and IndexOf(char), so it is noisier than CA1310; the shipped configuration sets it to warning because the rule asks for the choice to be written down, and a warning fails the build.
Exceptions:
- Compare text shown to users, such as a sorted customer list, with
StringComparison.CurrentCulture. ==and!=between two strings compare ordinally and need no argument. The rule covers the method forms.- The
charoverloads (Contains(char),StartsWith(char),EndsWith(char),IndexOf(char)) are ordinal, so the culture cannot change their result (VAR-026).CA1307still reportsContains(char)andIndexOf(char), so writeContains(c, StringComparison.Ordinal)andIndexOf(c, StringComparison.Ordinal);StartsWith(char)andEndsWith(char)need no argument.
Scope: String equality, ordering, searching and prefix tests on identifiers, keys, tokens, paths, roles and protocol values · Enforced: CA1309, CA1310, CA1307, CA1862, CA2251 · Sources: MS-STR, MS-CA, RT-GC
LANG-042¶
DO test for missing text with string.IsNullOrEmpty or, when whitespace counts as missing, string.IsNullOrWhiteSpace, instead of comparing with null, "" or Length == 0.
✅ Correct
public static bool HasEmail(Customer customer) => !string.IsNullOrWhiteSpace(customer.Email); // blank counts as missing
❌ Incorrect — a hand-written null-or-empty test
public static bool HasEmail(Customer customer) => customer.Email != null && customer.Email != ""; // manual null-or-empty test
Why: One call states what "missing" means and cannot forget either half of the test. It also informs the nullable analysis, so customer.Email is known to be non-null after a false result of IsNullOrWhiteSpace. The analyzer CA1820 reports a comparison with "" and recommends IsNullOrEmpty; the shipped configuration sets it to warning, and ReSharper reports the whole null-or-"" test.
Exceptions:
- Test with
is null(LANG-022) when an empty string is a valid value that must stay distinct fromnull.
Scope: Tests for missing or blank text · Enforced: CA1820, ReSharper: ReplaceWithStringIsNullOrEmpty · Config: resharper_replace_with_string_is_null_or_empty_highlighting · Sources: MS-CA, RS-INSPECT
LANG-043¶
DO pass CultureInfo.InvariantCulture when formatting or parsing values that machines read (files, logs, protocols, keys) and CultureInfo.CurrentCulture for text shown to users, and never rely on the implicit current culture; parse untrusted text with TryParse.
✅ Correct
using System.Globalization;
namespace Contoso.Orders;
public static class OrderCsv
{
public static string ToCsvAmount(decimal total) => total.ToString("F2", CultureInfo.InvariantCulture); // machine-read
public static string ToDisplayAmount(decimal total) => total.ToString("C", CultureInfo.CurrentCulture); // user-facing
public static bool TryParseQuantity(string text, out int quantity)
{
return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out quantity); // untrusted text
}
}
❌ Incorrect — the implicit current culture
public static string ToCsvAmount(decimal total) => total.ToString("F2"); // implicit current culture
Why: The current culture decides the decimal separator, the date order and the digits. A file written on a server set to a culture that uses a comma as decimal separator cannot be read by a machine set to another one, and a key built from a formatted number changes between machines. TryParse returns false for bad input instead of throwing, so untrusted text cannot cause an exception on the hot path.
Exceptions:
- An interpolated string for text shown to the user uses the current culture on purpose. Machine-read values use
string.Create(CultureInfo.InvariantCulture, $"{total:F2}")orToString(format, CultureInfo.InvariantCulture).
Scope: Formatting and parsing numbers, dates and other culture-sensitive values · Enforced: CA1305 · Sources: MS-STR, MS-CA, MS-CONV
LANG-044¶
DO normalize case with ToUpperInvariant or ToLowerInvariant, or better compare with StringComparison.OrdinalIgnoreCase, instead of calling culture-sensitive ToUpper or ToLower.
✅ Correct
public static string NormalizeSku(string sku) => sku.ToUpperInvariant(); // invariant case mapping
public static bool IsSameSku(string sku, string other) => string.Equals(sku, other, StringComparison.OrdinalIgnoreCase);
❌ Incorrect — culture-sensitive case mapping
public static string NormalizeSku(string sku) => sku.ToUpper(); // culture-sensitive case mapping
Why: ToUpper() follows the current culture. Under the Turkish culture (tr-TR) the letter i maps to a dotted capital İ, so "id".ToUpper() no longer equals "ID" and a key built that way differs between machines. ToUpperInvariant gives one result everywhere. When the goal is to compare, OrdinalIgnoreCase avoids creating a new string at all.
Exceptions:
- Use
ToUpper(CultureInfo.CurrentCulture)only for text displayed to a user in their language.
Scope: Case normalization and case-insensitive comparison · Enforced: CA1304, CA1311 · Sources: MS-STR, MS-CA
LINQ¶
These rules cover query syntax, layout and enumeration.
LANG-050¶
DO write LINQ queries in method syntax (orders.Where(...).Select(...)) and use query syntax only for joins, let clauses or several from clauses.
✅ Correct
public static IEnumerable<int> SelectShippedIds(IReadOnlyList<Order> orders)
{
return orders.Where(order => order.IsShipped).Select(order => order.Id);
}
✅ Correct — query syntax for a join
public static IEnumerable<string> SelectCustomerNames(IReadOnlyList<Order> orders, IReadOnlyList<Customer> customers)
{
IEnumerable<string> names =
from order in orders
join customer in customers on order.CustomerId equals customer.Id
select customer.Name;
return names;
}
❌ Incorrect — query syntax for a plain filter
public static IEnumerable<int> SelectShippedIds(IReadOnlyList<Order> orders)
{
return from order in orders where order.IsShipped select order.Id; // query syntax without a join
}
Why: Method syntax works for every operator, including Any, ToList and Count, which query syntax cannot express, so one style covers the whole code base. Query syntax is easier to read only where the compiler introduces range variables for you: joins, let and several from clauses.
Exceptions:
- None.
Scope: LINQ queries · Enforced: Manual · Sources: AV, GOOG, MS-CONV
LANG-051¶
DO when a LINQ method chain does not fit on one line, put each call on its own line starting with ., and put each clause of a multi-line query expression on its own line.
✅ Correct
public static IEnumerable<int> SelectLargeShippedIds(IReadOnlyList<Order> orders)
{
IEnumerable<int> ids = orders
.Where(order => order.IsShipped && order.Total > 1_000m)
.OrderByDescending(order => order.CreatedAt)
.Select(order => order.Id);
return ids;
}
✅ Correct — a multi-line query expression
public static IEnumerable<string> SelectCustomerNames(IReadOnlyList<Order> orders, IReadOnlyList<Customer> customers)
{
IEnumerable<string> names =
from order in orders
join customer in customers on order.CustomerId equals customer.Id
select customer.Name;
return names;
}
❌ Incorrect — two clauses on one line of a multi-line query
public static IEnumerable<int> SelectShippedIds(IReadOnlyList<Order> orders)
{
IEnumerable<int> ids =
from order in orders where order.IsShipped // two clauses on one line
select order.Id;
return ids;
}
Why: One call or clause per line makes each step of the pipeline a line you can read, comment out or change in a diff. A query that sits entirely on one line is not reported; the rule applies once the query spans lines. The chain layout is a formatter setting for ReSharper (chop_if_long); the build checks the query-clause layout.
Exceptions:
- A chain that fits within the 120-character line limit (FMT-040) may stay on one line.
Scope: Multi-line LINQ method chains and query expressions · Enforced: IDE0055 · Config: csharp_new_line_between_query_expression_clauses, resharper_csharp_wrap_chained_method_calls · Sources: MS-CONV, MS-IDE-CSFMT, AV, GOOG
LANG-052¶
DO materialize a query with ToList or ToArray before enumerating it more than once, and test whether a sequence has elements with Any() or, on a materialized collection, with Count or Length, never with Count() > 0.
✅ Correct
public static bool HasLargeOrders(IEnumerable<Order> orders) => orders.Any(order => order.Total > 1_000m);
public static string Summarize(IEnumerable<OrderLine> lines)
{
List<OrderLine> activeLines = [.. lines.Where(line => line.Quantity > 0)]; // materialized once
return $"{activeLines.Count} lines, {activeLines.Sum(line => line.Amount):N2}";
}
❌ Incorrect — Count() to test for elements, and a query enumerated twice
public static bool HasOrders(IEnumerable<Order> orders) => orders.Count() > 0; // Count() to test for elements
public static string Summarize(IEnumerable<OrderLine> lines)
{
IEnumerable<OrderLine> active = lines.Where(line => line.Quantity > 0);
return $"{active.Count()} lines, {active.Sum(line => line.Amount):N2}"; // active is enumerated twice
}
Why: A LINQ query is a recipe that runs each time you enumerate it. Enumerating twice runs the filter twice, and a source such as a database query or a stream can return different results or fail the second time. Count() > 0 walks the whole sequence to answer a yes-or-no question; Any() stops at the first element. On a List<T> or an array, Count and Length are stored values.
Exceptions:
- Do not materialize a sequence that is enumerated once, or one that is too large to hold in memory; stream it.
Scope: Enumerating sequences more than once and testing for elements · Enforced: CA1827, CA1829, CA1860, CA1851, ReSharper: PossibleMultipleEnumeration · Config: resharper_possible_multiple_enumeration_highlighting · Sources: MS-CA, AV, RS-INSPECT
C# 12-14 features and rarely used statements¶
These rules cover extension blocks, goto, top-level statements, null-conditional assignment and checked arithmetic.
LANG-060¶
DO declare new extension members in C# 14 extension(...) blocks inside the extension class that NAM-127 names, and add an extension only for a type you cannot change.
C# 14:
extensionblocks need C# 14. With aLangVersionbelow 14, declare a static method whose first parameter carriesthis:public static string Truncate(this string text, int maxLength).
✅ Correct
namespace Contoso.Orders;
public static class StringExtensions
{
extension(string text)
{
public string Truncate(int maxLength)
{
ArgumentOutOfRangeException.ThrowIfNegative(maxLength);
return text.Length <= maxLength ? text : text[..maxLength]; // string is a type you cannot change
}
}
}
❌ Incorrect — an extension for a type this codebase owns
namespace Contoso.Orders;
public static class OrderExtensions
{
extension(Order order) // extend your own type directly
{
public bool HasLines() => order.Lines.Count > 0;
}
}
Why: An extension block declares the receiver once and can hold extension properties as well as methods; the older this form can only declare methods. A member added to a type you own belongs in the type, where its callers find it and where it can reach private state. An extension exists to add members to a type you cannot edit, such as a framework type or a type from another package. NAM-127 owns the name of the extension class (StringExtensions for string), and NAM-137 owns the name of the receiver. The analyzer CA1034 reports the block as a nested public type; the shipped configuration sets it to suggestion.
Exceptions:
- Extend a type you own but cannot change in this assembly, such as a generated type from another project.
Scope: Extension members (naming: NAM-127, NAM-137) · Enforced: Manual · Sources: MS-LANG-14, MS-FDG-EXT, AV, GOOG
LANG-061¶
AVOID goto and statement labels; write a loop, an early return or a local function instead.
✅ Correct
private const int MaxAttempts = 3;
public static bool TryPay(Func<bool> pay)
{
for (int i = 1; i <= MaxAttempts; i++) // bounded loop, returns on success
{
if (pay())
{
return true;
}
}
return false;
}
❌ Incorrect — a goto retry
private const int MaxAttempts = 3;
public static bool TryPay(Func<bool> pay)
{
int attempt = 0;
bool paid;
RetryPayment: // label for a goto retry
paid = pay();
attempt++;
if (!paid && attempt < MaxAttempts)
{
goto RetryPayment; // goto instead of a loop
}
return paid;
}
Why: A loop states its bound and exit in one place; a goto forces the reader to find the label and follow the jump, and a label breaks the indentation of the block it sits in. An early return or a local function expresses the same exits with a name the reader can read. Overflow-checked arithmetic is a separate rule (LANG-064).
Exceptions:
- A
goto caseorgoto defaultinside aswitchstatement is allowed when no loop or expression expresses the flow.
Scope: goto statements and labels (overflow-checked arithmetic: LANG-064) · Enforced: Manual · Sources: RT-STYLE, AV
LANG-062¶
DO write the entry point of an application as top-level statements in Program.cs, and never use top-level statements in libraries or in any other file.
✅ Correct
TimeProvider timeProvider = TimeProvider.System;
var order = new Order(7, timeProvider.GetUtcNow());
Console.WriteLine($"Order created at {order.CreatedAt:O}");
❌ Incorrect — a Main method in the entry-point file
namespace Contoso.Orders;
internal static class Program
{
private static void Main() // Main method instead of top-level statements
{
var order = new Order(7, TimeProvider.System.GetUtcNow());
Console.WriteLine($"Order created at {order.CreatedAt:O}");
}
}
Why: Top-level statements remove the class, the Main signature and one level of indentation from the file that starts the application, so the first line of the file is the first line that runs. A library has no entry point, and a second file with top-level statements is a compile error. IDE0210 reports a Main method in an executable project; the compiler rejects top-level statements in a library or a second file.
Exceptions:
- None.
Scope: Application entry points · Enforced: IDE0210 · Config: csharp_style_prefer_top_level_statements · Sources: MS-IDE, MS-CONV
LANG-063¶
DO write a null-conditional assignment (customer?.Email = email;) instead of an if (customer is not null) block around a single assignment.
C# 14: Null-conditional assignment needs C# 14. With a
LangVersionbelow 14,customer?.Email = email;does not compile; writeif (customer is not null)around the assignment.
✅ Correct
namespace Contoso.Orders;
public sealed class ContactCard
{
public string Email { get; set; } = "";
public static void UpdateEmail(ContactCard? card, string email) => card?.Email = email; // skipped when null
}
❌ Incorrect — a null check around one assignment
namespace Contoso.Orders;
public sealed class ContactCard
{
public string Email { get; set; } = "";
public static void UpdateEmail(ContactCard? card, string email)
{
if (card is not null) // null check around one assignment
{
card.Email = email;
}
}
}
Why: The operator ?. on the left of an assignment evaluates the right-hand side only when the receiver is not null. It replaces four lines with one and keeps the single assignment visible. Use it when the only action is that assignment; a block that does more than one thing keeps its if.
Exceptions:
- Keep the
ifwhen the block holds more than one statement or needs anelsebranch.
Scope: Assignments to members of objects that may be null · Enforced: Manual · Sources: MS-LANG-14
LANG-064¶
DO use a checked expression or block wherever an integer overflow must throw instead of wrapping (sizes, money in minor units, counters used for allocation).
✅ Correct
public static int CalculateAmountCents(int quantity, int unitPriceCents) => checked(quantity * unitPriceCents);
✅ Correct — a checked block for several operations
public static int SumQuantities(IReadOnlyList<OrderLine> lines)
{
int total = 0;
checked
{
foreach (OrderLine line in lines)
{
total += line.Quantity; // overflow throws OverflowException
}
}
return total;
}
❌ Incorrect — arithmetic that can wrap
public static int CalculateAmountCents(int quantity, int unitPriceCents) =>
quantity * unitPriceCents; // can wrap silently
Why: Integer arithmetic is unchecked by default, so a product above int.MaxValue wraps to a negative or smaller number and the program goes on with a wrong amount, size or allocation length. checked turns that into an OverflowException at the calculation. The compiler switch <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> makes every integer operation in a project checked; use it when all arithmetic in the project must throw, and accept the cost of the check on each operation. No diagnostic reports arithmetic that can overflow, so reviewers check it.
Exceptions:
- Code that relies on wrap-around, such as a hash calculation, writes
unchecked(...)so the intent is visible.
Scope: Integer arithmetic whose overflow would corrupt a size, an amount or an allocation (goto: LANG-061) · Enforced: Manual · Sources: MS-CHECKED
Related¶
- Layout and Formatting: the 120-character line limit (FMT-040) and initializer layout (FMT-050, FMT-052).
- Naming Types and Members: extension classes and receivers (NAM-127, NAM-137).
- Variables: Types, Literals and Nullability: when to use
var(VAR-010) and the empty string (VAR-032). - Variables: Fields, Properties and Collections: expression-bodied properties (VAR-524), collection expressions (VAR-531),
outvariables (VAR-550) andusingdeclarations (VAR-551). - Types and Members: static members (TYPE-026).
- Exceptions and Error Handling: guard clauses (ERR-014) and disposal with
using(ERR-020). - Secure Coding: constant-time comparison of secrets (SEC-012) and log templates (SEC-073).
- Tooling and Enforcement: the shipped
.editorconfigand the table of rules that only reviewers check.
Sources¶
The keys cited in this chapter are listed on the Sources page.
MS-IDE-OPTIONS, MS-CONV, MS-IDE, MS-IDE-CSFMT, MS-CA, MS-STR, MS-LANG-12, MS-LANG-14, MS-CHECKED, MS-FDG-EXT, RT-STYLE, RT-EC, RT-GC, ROSLYN, AV, GOOG, RS-BODIES, RS-INSPECT.
Previous: Variables: Fields, Properties and Collections · Home · Next: Types and Members