Skip to content

Variables: Fields, Properties and Collections

Rule prefix: VAR · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID

Home · Rule index · Naming cheat sheet

This chapter shows how to declare the members and special forms that hold data: constants, fields, properties, arrays and collections, tuples, records, structs, enums, and the declaration forms that need care (out variables, using declarations, ref locals, spans, shadowing and closures). Locals, literals, numeric and date types, strings and nullability are on page 05.

Names for these members are on page 03 and page 04; this chapter covers how to declare them (const or static readonly, readonly, initialisation). Choosing between a record, class and struct is on page 08 (TYPE-020), and thread safety of shared state is on page 11.

Several rules rely on newer syntax: collection expressions ([1, 2, 3], [..first, ..second]), primary constructors, the field keyword in property accessors, target-typed new and the discard _. Rules that need C# 12 or later carry a version callout.

Ten rules have no tool check and are checked in review: VAR-527, VAR-528, VAR-533, VAR-542, VAR-544, VAR-545, VAR-548, VAR-554, VAR-556 and VAR-557 (TOOL-018). VAR-511 and VAR-552 are checked by Rider and ReSharper only. VAR-536 and VAR-547 are CONSIDER rules that ship at suggestion severity.

You want to declare Rules
A constant, as a field or a local VAR-510, VAR-511
An instance or static field VAR-512 to VAR-515
A property VAR-520 to VAR-528
An array, list, set, queue, stack or dictionary VAR-530 to VAR-536
A tuple, record, struct or anonymous type VAR-540 to VAR-544
An enum, a delegate, a generic type parameter, dynamic or object VAR-545 to VAR-548
An out variable or a disposable resource VAR-550 to VAR-552
A pattern, a ref local, a span or a stackalloc buffer VAR-553 to VAR-555
A local or lambda that must not hide a member or capture a loop counter VAR-556, VAR-557

Rule index

ID Level Rule Enforced
VAR-510 DO declare a public const only for a value that can never change (mathematical or protocol constants), use a private or internal const for other compile-time literals such as business limits, and use static readonly for public values that may change between versions, values computed at run time and non-primitive values. CA1802
VAR-511 DO declare a local whose value is a compile-time constant and never changes as const. ReSharper: ConvertToConstant.Local
VAR-512 DO declare every instance field private and expose state through properties; public instance fields are allowed only in structs that mirror a native or wire layout. CA1051
VAR-513 DO make every static field readonly or private, and never expose a mutable static field outside its type. CA2211
VAR-514 DO keep per-thread state in ThreadLocal<T> and per-async-flow state in AsyncLocal<T>, never initialize a [ThreadStatic] field in its declaration, and use Interlocked, Volatile or a lock instead of volatile fields. CA2019
VAR-515 DO initialize a field in its declaration when its value does not depend on constructor arguments, and never initialize a field to its default value (0, false, null, default). CA1805, ReSharper: RedundantDefaultMemberInitializer
VAR-520 DO declare a property that only reads and writes its value as an auto-property (public decimal Total { get; set; }). IDE0032, ReSharper: ConvertToAutoProperty
VAR-521 DO declare a property that callers must not change after construction as get-only ({ get; }) or init, and never declare a property with only a setter. CA1044, ReSharper: AutoPropertyCanBeMadeGetOnly.Global
VAR-522 DO mark a property required (usually with init) when every caller must set it during object initialization, instead of adding a constructor parameter for it. CS8618
VAR-523 DO use the C# 14 field keyword in an accessor that needs logic instead of declaring a backing field, and write get; for an accessor that only returns field. IDE0360, ReSharper: ReplaceWithFieldKeyword
VAR-524 DO write a get-only property, indexer or accessor whose body is a single expression that fits within the line limit, wrapped at => if needed, as an expression body (public decimal Total => _lines.Sum(line => line.Amount);), and as a block body otherwise. IDE0025, IDE0026, IDE0027, ReSharper: ArrangeAccessorOwnerBody
VAR-525 DO initialize a collection or other non-nullable reference-type property in its declaration (= [];, = new();, = "";) or make it required, so it is never null. CS8618
VAR-526 DO use a method instead of a property when the operation does I/O, takes noticeable time, has side effects, can throw for a valid object state, or returns a new array or a snapshot on each call. CA1819
VAR-527 DO reference a static member through the type that declares it (OrderService.MaxLinesPerOrder), never through a derived type or an instance. Manual
VAR-528 DO expose static state through a get-only static auto-property (public static TimeSpan PaymentTimeout { get; } = TimeSpan.FromSeconds(30);) or a static readonly field for an immutable value, keep mutable static state in a private static field changed only by methods, and never give a static property a public setter. Manual
VAR-530 DO declare arrays as T[], create them with collection expressions (int[] quantities = [1, 2, 3];), and use jagged arrays (T[][]) instead of multidimensional arrays (T[,]) in public APIs. IDE0300, CA1814
VAR-531 DO create a list, set, queue or stack with a collection expression (List<OrderLine> lines = [first, second];, [..existing, extra]), passing a capacity or comparer through the constructor only when one is needed. IDE0028, IDE0303, IDE0304, IDE0306, ReSharper: UseCollectionExpression
VAR-532 DO write an empty collection as [] wherever the target type allows it, instead of new T[0], Array.Empty<T>(), Enumerable.Empty<T>() or new List<T>(). IDE0301, CA1825
VAR-533 DO populate a dictionary with an index initializer (["SKU-1"] = 9.99m) and pass a StringComparer (usually StringComparer.Ordinal or OrdinalIgnoreCase) whenever the key is a string. Manual
VAR-534 DO store data that never changes after construction in an immutable or frozen collection (ImmutableArray<T>, FrozenSet<T>, FrozenDictionary<TKey, TValue>), created with a collection expression or a ToFrozenSet, ToFrozenDictionary or ToImmutable... call. IDE0303, IDE0304
VAR-535 DO expose collections from public members as IReadOnlyList<T>, IReadOnlyCollection<T>, IReadOnlyDictionary<TKey, TValue> or, for lazily produced sequences, IEnumerable<T>, never as List<T> or as a settable collection property. CA1002, CA2227
VAR-536 CONSIDER use the index operator ^ and the range operator .. (lines[^1], sku[4..]) instead of Length - 1 arithmetic and Substring or Slice calls. IDE0056, IDE0057
VAR-540 DO write tuple types with the tuple syntax and named elements ((int Count, decimal Total)), read elements by name, and never use Tuple<T1, T2> or ValueTuple<T1, T2> spelled out. IDE0033
VAR-541 DO deconstruct a tuple or record into separately declared locals (var (count, total) = Summarize(order);) instead of keeping a tuple local and reading its elements. IDE0042, ReSharper: ArrangeVarKeywordsInDeconstructingDeclaration
VAR-542 DO declare a reference record with the record keyword (not record class), use positional syntax only for small immutable data, and use a nominal record with required or init properties when it has more than about four members. Manual
VAR-543 DO declare a struct that represents a value readonly (readonly struct, readonly record struct) and mark every member of a mutable struct that does not change state readonly. IDE0250, IDE0251
VAR-544 DO use an anonymous type only for a projection that stays inside one method, and use a named record when the data is returned, stored in a field or passed to another method. Manual
VAR-545 DO NOT declare a variable, parameter or return type as dynamic except for COM or dynamic-language interop, or as object where a generic type parameter or a specific type expresses the same thing. Manual
VAR-546 DO keep int as the underlying type of an enum unless interop or a storage format needs another type, give the zero value a meaning (None, Unknown or the natural default), and assign an explicit value to every member that is persisted or sent between systems. CA1028, CA1008
VAR-547 CONSIDER typing delegate variables and parameters as Func<> or Action<>, and marking a lambda that captures nothing static. IDE0320
VAR-548 DO add to each type parameter exactly the constraints the generic code needs (where T : notnull, class, struct, an interface or new()), and no constraint the code does not use. Manual
VAR-550 DO declare an out variable inline at the call (out var quantity; an explicit type is accepted) and pass out _ for a result you do not need. IDE0018, ReSharper: InlineOutVariableDeclaration
VAR-551 DO declare a disposable resource with a using declaration (using var stream = File.OpenRead(path);) unless it must be released before the end of the enclosing block, in which case use a using block. IDE0063, ReSharper: ConvertToUsingDeclaration
VAR-552 DO release a resource that implements IAsyncDisposable with await using (await using FileStream stream = ...;). ReSharper: UseAwaitUsing
VAR-553 DO use relational (< 0), logical (and, or, not) and extended property patterns ({ Lines.Count: 0 }) instead of chained == comparisons, !(x is T) and nested property patterns. IDE0078, IDE0083, IDE0170
VAR-554 DO use ref locals, ref returns and scoped only on a measured hot path to avoid copying large structs, and prefer ref readonly when the caller must not write through the reference. Manual
VAR-555 DO slice and buffer data with Span<T> and ReadOnlySpan<T> instead of pointers and unsafe code, and use stackalloc only with a small constant size and never inside a loop. CA2014
VAR-556 DO NOT declare a local, parameter or lambda parameter with the name of a field, property or outer local that is in scope. Manual
VAR-557 DO NOT capture the counter of a for loop in a lambda or local function; copy it to a local declared inside the loop body and capture that local. Manual

Fields and constants

These rules cover constants, instance and static fields, per-thread state and field initialisation.

VAR-510

DO declare a public const only for a value that can never change (mathematical or protocol constants), use a private or internal const for other compile-time literals such as business limits, and use static readonly for public values that may change between versions, values computed at run time and non-primitive values.

✅ Correct

public const int HttpsPort = 443; // protocol constant: it can never change, so public const

private const int MaxLinesPerOrder = 50; // business limit: private const, no outside copy

public static readonly TimeSpan DefaultPaymentTimeout = TimeSpan.FromSeconds(30); // computed, so static readonly

public static bool IsFull(Order order) => order.Lines.Count >= MaxLinesPerOrder;

❌ Incorrect — private static readonly field that holds a literal

private static readonly int MaxLinesPerOrder = 50; // literal value in static readonly

public static bool IsFull(Order order) => order.Lines.Count >= MaxLinesPerOrder;

Why: The compiler copies a const value into every caller. If a library changes a public const, code compiled against the old assembly keeps the old value until it is rebuilt. A static readonly field is read at run time, so a new version takes effect without a rebuild, and it accepts values the compiler cannot fold, such as TimeSpan.FromSeconds(30). A private or internal const has no callers outside the assembly, so a business limit such as MaxLinesPerOrder can stay const and still change in the next release. A public const is for values that never change, such as the HTTPS port or Math.PI; a business limit that other assemblies need is a public static readonly field or a property.

Exceptions: A public static readonly field initialized with a literal stays as it is when the value may change in a later version. With the .NET 10 SDK analyzers, CA1802 reports the private field in the example above and does not report public ones.

See also: NAM-214 (constants), NAM-211 (private static readonly fields), NAM-213 (public static readonly fields).

Scope: const fields, static readonly fields and readonly instance fields · Enforced: CA1802 · Sources: MS-FDG-FIELD, MS-CA, GOOG, RT-STYLE

VAR-511

DO declare a local whose value is a compile-time constant and never changes as const.

✅ Correct

public static bool QualifiesForFreeShipping(Order order)
{
    const decimal freeShippingThreshold = 50m; // compile-time constant, so const

    return order.Total >= freeShippingThreshold;
}

❌ Incorrect — local that is never reassigned but is not const

public static bool QualifiesForFreeShipping(Order order)
{
    decimal freeShippingThreshold = 50m; // never reassigned, should be const

    return order.Total >= freeShippingThreshold;
}

Why: A const local tells the reader that the value is fixed, and the compiler rejects any later assignment. No Roslyn diagnostic asks for it, so the build does not fail; Rider and ReSharper highlight the missing const.

Exceptions: A local whose value is computed at run time, or whose type cannot be const (TimeSpan, arrays, other reference types), stays a normal local.

See also: NAM-216 (local constants: camelCase preferred, PascalCase accepted).

Scope: Local values computed at compile time · Enforced: ReSharper: ConvertToConstant.Local · Config: resharper_convert_to_constant_local_highlighting · Sources: MS-IDNAME, GOOG, RS-INSPECT

VAR-512

DO declare every instance field private and expose state through properties; public instance fields are allowed only in structs that mirror a native or wire layout.

✅ Correct

namespace Contoso.Orders;

public sealed class ShippingLabel(string trackingNumber)
{
    private int _printCount; // state stays private

    public string TrackingNumber { get; } = trackingNumber; // exposed as a property

    public int MarkPrinted()
    {
        _printCount++;

        return _printCount;
    }
}

❌ Incorrect — public instance field

namespace Contoso.Orders;

public sealed class ShippingLabel
{
    public string TrackingNumber = ""; // public instance field
}

Why: Replacing a public field with a property later is a binary-breaking change, because callers compiled against the field throw MissingFieldException at run time until they are rebuilt. A property lets the type add validation, change notification or different storage without breaking callers, and serializers such as System.Text.Json skip public fields by default. Keeping every field private costs nothing and keeps that choice open.

Exceptions: A struct that mirrors a native or wire layout declares public fields (NAM-203). The shipped configuration sets dotnet_code_quality.CA1051.exclude_structs = true so CA1051 skips structs.

See also: NAM-200 (private field names), NAM-202 (internal field names), NAM-203 (public and protected field names).

Scope: Instance fields of classes, records and structs (interop structs excepted) · Enforced: CA1051 · Config: dotnet_code_quality.CA1051.exclude_structs · Sources: MS-FDG-FIELD, MS-CA, AV

VAR-513

DO make every static field readonly or private, and never expose a mutable static field outside its type.

✅ Correct

namespace Contoso.Orders;

public static class OrderCounters
{
    private static int _ordersPlaced; // mutable, so private

    public static int OrdersPlaced => _ordersPlaced;

    public static int Increment() => Interlocked.Increment(ref _ordersPlaced);
}

❌ Incorrect — mutable public static field

namespace Contoso.Orders;

public static class OrderCounters
{
    public static int OrdersPlaced; // mutable public static field
}

Why: A mutable public static field is global state that any caller can overwrite and that every thread shares. Behind a private field, the type decides how it changes; here Interlocked.Increment makes the update atomic. Thread-safe handling of shared static state is covered by ASYNC-021.

Exceptions: A public static readonly field that holds an immutable value is allowed (NAM-213). A static readonly field that holds a mutable object is still shared mutable state, so keep it private.

See also: NAM-210 (static field names), ASYNC-021 (protecting shared static state).

Scope: Static fields · Enforced: CA2211 · Sources: MS-CA, MS-FDG-FIELD

VAR-514

DO keep per-thread state in ThreadLocal<T> and per-async-flow state in AsyncLocal<T>, never initialize a [ThreadStatic] field in its declaration, and use Interlocked, Volatile or a lock instead of volatile fields.

✅ Correct

private static readonly AsyncLocal<int?> CorrelationDepth = new(); // follows the async flow

public static int EnterScope()
{
    int depth = (CorrelationDepth.Value ?? 0) + 1;
    CorrelationDepth.Value = depth;

    return depth;
}

✅ Correct — per-thread state with a start value

private static readonly ThreadLocal<int> Depth = new(() => 1); // factory runs once per thread

public static int Enter()
{
    Depth.Value++;

    return Depth.Value;
}

❌ Incorrect — inline initializer on a [ThreadStatic] field, and a volatile field

[ThreadStatic]
private static int _depth = 1; // inline initializer runs on one thread only

public static int Depth => _depth;

private volatile bool _isRunning; // volatile instead of Interlocked, Volatile or a lock

public bool IsRunning => _isRunning;

Why: The initializer of a [ThreadStatic] field runs once, so only the first thread that touches the type sees 1; every other thread starts at 0. ThreadLocal<T> takes a factory that runs per thread, and AsyncLocal<T> keeps its value across await, which a thread-static field loses when the continuation resumes on another thread. A volatile field such as volatile bool _isRunning only makes single reads and writes visible to other threads. It does not make _count++ atomic and it hides which accesses need ordering. Volatile.Read and Volatile.Write mark the exact access, Interlocked makes the update atomic, and a lock protects several fields together.

Exceptions: To give each thread a start value without ThreadLocal<T>, assign the [ThreadStatic] field on first use inside the method that needs it, not in the declaration.

See also: NAM-212 (thread-static field names), ASYNC-021 (shared static state).

Scope: Per-thread and per-async-flow state; volatile fields · Enforced: CA2019 · Sources: MS-CA, RT-STYLE

VAR-515

DO initialize a field in its declaration when its value does not depend on constructor arguments, and never initialize a field to its default value (0, false, null, default).

✅ Correct

private readonly List<OrderLine> _lines = []; // value needs no constructor argument
private int _retryCount; // already 0

public int AddLine(OrderLine line)
{
    _lines.Add(line);

    return _lines.Count;
}

public int RecordRetry()
{
    _retryCount++;

    return _retryCount;
}

❌ Incorrect — field initialized to its default value

private int _retryCount = 0; // explicit default value

public int RecordRetry()
{
    _retryCount++;

    return _retryCount;
}

Why: The runtime sets every field to its default before any code runs, so = 0 adds an assignment that changes nothing and makes the reader check that the value really is the default. A value that does not depend on constructor arguments belongs in the declaration, so every constructor gets it and none can forget it.

Exceptions: A value that depends on a constructor argument is assigned in the constructor or from a primary-constructor parameter (public int CustomerId { get; } = customerId;).

See also: NAM-200 (private field names), VAR-014 (target-typed new() in initializers).

Scope: Field initializers and constructor assignments · Enforced: CA1805, ReSharper: RedundantDefaultMemberInitializer · Config: resharper_redundant_default_member_initializer_highlighting · Sources: MS-CA, MS-CONV, RS-INSPECT

Properties

These rules cover auto-properties, get-only, init and required properties, the field keyword, expression bodies, and static properties.

VAR-520

DO declare a property that only reads and writes its value as an auto-property (public decimal Total { get; set; }).

✅ Correct

public decimal Total { get; private set; } // auto-property: no field to declare

public void Recalculate(IEnumerable<OrderLine> lines)
{
    Total = lines.Sum(line => line.Amount);
}

❌ Incorrect — backing field that only stores the value

private decimal _total; // trivial backing field

public decimal Total
{
    get => _total;
    private set => _total = value;
}

public void Recalculate(IEnumerable<OrderLine> lines)
{
    Total = lines.Sum(line => line.Amount);
}

Why: A field that only mirrors a property is a second name for the same storage and one more line to keep in step. An auto-property states the same thing in one line and can still narrow a setter (private set).

Exceptions: Declare a backing field when another member reads or writes the same storage (NAM-204). When an accessor needs logic, prefer the field keyword (VAR-523).

Scope: Properties that only read or write a field · Enforced: IDE0032, ReSharper: ConvertToAutoProperty · Config: dotnet_style_prefer_auto_properties, resharper_convert_to_auto_property_highlighting · Sources: MS-IDE, RT-EC, RS-INSPECT

VAR-521

DO declare a property that callers must not change after construction as get-only ({ get; }) or init, and never declare a property with only a setter.

✅ Correct

namespace Contoso.Orders;

public sealed class ShippingQuote(string carrier)
{
    public decimal Amount { get; init; } // set in an object initializer, then fixed

    public string Carrier { get; } = carrier; // set once from the primary constructor
}

❌ Incorrect — property with only a setter

namespace Contoso.Orders;

public sealed class ShippingQuote
{
    private string _carrier = "";

    public string Carrier // property without a getter
    {
        set => _carrier = value;
    }

    public string Describe() => $"Quote via {_carrier}";
}

Why: A get-only or init property keeps an object from changing under its readers, so a value read once stays valid. A set-only property lets callers write a value they cannot read back, which no caller expects from something that looks like a property; a method such as SetCarrier states that intent.

Exceptions: An init accessor allows assignment only in an object initializer, a with expression or the constructor, so it counts as "not changeable after construction".

Scope: Properties whose value must not change after construction or initialisation · Enforced: CA1044, ReSharper: AutoPropertyCanBeMadeGetOnly.Global · Config: resharper_auto_property_can_be_made_get_only_global_highlighting, resharper_auto_property_can_be_made_get_only_local_highlighting · Sources: MS-FDG-PROPERTY, MS-CONV, MS-CA, RS-INSPECT

VAR-522

DO mark a property required (usually with init) when every caller must set it during object initialization, instead of adding a constructor parameter for it.

✅ Correct

namespace Contoso.Orders;

public sealed class ShippingAddress
{
    public required string Street { get; init; } // callers must set it

    public required string City { get; init; }

    public string? Region { get; init; } // optional, so nullable
}

✅ Correct — creating an object whose required members are all set

public static Customer CreateCustomer()
{
    return new()
    {
        Id = 7, // required members: omitting one is a compile error
        Name = "Contoso Test Customer"
    };
}

❌ Incorrect — non-nullable property that is neither required nor initialized

namespace Contoso.Orders;

public sealed class ShippingAddress
{
    public string Street { get; init; } // non-nullable, not required, never initialized

    public string? Region { get; init; }
}

Why: required moves the check to compile time: a caller that forgets Street gets an error at the new expression, and the property can be non-nullable without a constructor to fill it. Types that capture dependencies (services) use a primary constructor instead (LANG-012); data types use required and init. IDE0290 suggests primary constructors; use them for services, not for data properties.

Exceptions: A type that must validate its inputs together (for example, a range whose start must not exceed its end) takes constructor parameters and checks them there.

See also: VAR-051 (nullable reference types), VAR-525 (initializing collection properties).

Scope: Properties that every creator of the object must set · Enforced: CS8618 · Sources: MS-CONV, AV, MS-LANG-12

VAR-523

DO use the C# 14 field keyword in an accessor that needs logic instead of declaring a backing field, and write get; for an accessor that only returns field.

C# 14: The field keyword is new in C# 14. With a LangVersion below 14, field is an ordinary identifier and the accessor needs an explicit backing field (NAM-204).

✅ Correct

public string Sku
{
    get; // returns the compiler-generated field
    set => field = value.Trim().ToUpperInvariant();
} = "";

❌ Incorrect — accessor that only returns field

public string Sku
{
    get => field; // accessor only returns field
    set => field = value.Trim();
} = "";

Why: field removes the second name for the same storage: no other member can touch a _sku field by mistake, and the property keeps the auto-property shape for the accessor that needs no logic. IDE0360 asks for get; when an accessor only returns field.

Exceptions: A member of your own type named field clashes with the keyword; rename it, or write @field for the member and field for the backing field. Keep an explicit backing field when another member reads or writes the same storage (NAM-204).

Scope: Properties whose accessor needs validation, normalization or change notification · Enforced: IDE0360, ReSharper: ReplaceWithFieldKeyword · Config: csharp_style_prefer_simple_property_accessors, resharper_replace_with_field_keyword_highlighting · Sources: MS-LANG-14, MS-IDE, AV

VAR-524

DO write a get-only property, indexer or accessor whose body is a single expression that fits within the line limit, wrapped at => if needed, as an expression body (public decimal Total => _lines.Sum(line => line.Amount);), and as a block body otherwise.

✅ Correct

private readonly List<OrderLine> _lines = [];

public int LineCount => _lines.Count; // one expression on one line

public OrderLine this[int index] => _lines[index];

❌ Incorrect — block bodies for one-expression accessors

private readonly List<OrderLine> _lines = [];

public int LineCount // block body for a one-expression getter
{
    get { return _lines.Count; }
}

public int Capacity
{
    get // accessor block with one expression
    {
        return _lines.Capacity;
    }
    set => _lines.Capacity = value;
}

Why: A single-expression getter reads as a formula; the braces, get and return around it are noise. The IDE default, ReSharper, the Google guide and the Aviva guidelines prefer the expression body over a block body for single-expression properties.

Exceptions: An expression that does not fit within the line limit even after wrapping at => (FMT-041) becomes a block body, so the logic reads top to bottom. Methods and constructors follow LANG-010.

Scope: Get-only properties, indexers and accessors · Enforced: IDE0025, IDE0026, IDE0027, ReSharper: ArrangeAccessorOwnerBody · Config: csharp_style_expression_bodied_properties, csharp_style_expression_bodied_indexers, csharp_style_expression_bodied_accessors, resharper_csharp_accessor_owner_body, resharper_arrange_accessor_owner_body_highlighting · Sources: MS-IDE-OPTIONS, RS-BODIES, GOOG, AV

VAR-525

DO initialize a collection or other non-nullable reference-type property in its declaration (= [];, = new();, = "";) or make it required, so it is never null.

✅ Correct

public IReadOnlyList<string> Tags { get; init; } = []; // empty, never null

public string Notes { get; init; } = "";

❌ Incorrect — reference-type property left null

public IReadOnlyList<string> Tags { get; init; } // left null

Why: Callers can then iterate Tags without a null check, and the compiler's nullable analysis stays true: a non-nullable property that holds null produces CS8618 at the declaration and a NullReferenceException at the first use.

Exceptions: A property that can legitimately be absent is declared nullable (string? Region). A property that holds a collection is empty, not null (TYPE-024).

See also: VAR-522 (required), VAR-051 (nullable reference types).

Scope: Properties of collection and other reference types · Enforced: CS8618 · Sources: MS-NRT, GOOG, MS-FDG-COLL

VAR-526

DO use a method instead of a property when the operation does I/O, takes noticeable time, has side effects, can throw for a valid object state, or returns a new array or a snapshot on each call.

✅ Correct

namespace Contoso.Orders;

public sealed class OrderExport(Order order)
{
    public OrderLine[] CreateSnapshot() => [.. order.Lines]; // a method: the name says it copies
}

❌ Incorrect — property that returns a new array

namespace Contoso.Orders;

public sealed class OrderExport(Order order)
{
    public OrderLine[] Snapshot => [.. order.Lines]; // property returns a new array
}

Why: Callers treat a property as a cheap field read that can be repeated: export.Snapshot[0] inside a loop would copy the whole array on every pass. A property that queries a database, reads a file or throws for a valid object state breaks the same expectation. A method name signals the cost.

Exceptions: A property may return a cached IReadOnlyList<T> or ImmutableArray<T> that is built once, because reading it copies nothing.

See also: ERR-013 (the few members that may throw from a getter).

Scope: Members that could be either a property or a method · Enforced: CA1819 · Sources: MS-FDG-PROPERTY, MS-CA, AV

VAR-527

DO reference a static member through the type that declares it (OrderService.MaxLinesPerOrder), never through a derived type or an instance.

✅ Correct

namespace Contoso.Orders;

public class ShippingRate(decimal amount)
{
    public static readonly decimal MinimumCharge = 4.99m;

    public decimal Amount { get; } = amount;
}

public sealed class ExpressShippingRate(decimal amount) : ShippingRate(amount)
{
    public bool IsBelowMinimum() => Amount < ShippingRate.MinimumCharge; // declaring type
}

❌ Incorrect — static member read through a derived type

namespace Contoso.Orders;

public class ShippingRate(decimal amount)
{
    public static readonly decimal MinimumCharge = 4.99m;

    public decimal Amount { get; } = amount;
}

public sealed class ExpressShippingRate(decimal amount) : ShippingRate(amount)
{
    public bool IsBelowMinimum() => Amount < ExpressShippingRate.MinimumCharge; // static member via derived type
}

Why: ExpressShippingRate.MinimumCharge suggests that the derived type declares or overrides the value. It does not: the compiler resolves it to ShippingRate.MinimumCharge. If someone later adds a hiding member with the same name to the derived type, this call site silently changes meaning. Naming the declaring type shows where the value lives.

See also: VAR-528 (declaring static state), VAR-513 (static fields).

Scope: References to static members · Enforced: Manual · Sources: MS-CONV

VAR-528

DO expose static state through a get-only static auto-property (public static TimeSpan PaymentTimeout { get; } = TimeSpan.FromSeconds(30);) or a static readonly field for an immutable value, keep mutable static state in a private static field changed only by methods, and never give a static property a public setter.

✅ Correct

namespace Contoso.Orders;

public static class OrderDefaults
{
    public static TimeSpan PaymentTimeout { get; } = TimeSpan.FromSeconds(30); // get-only static auto-property
}

❌ Incorrect — static property with a public setter

namespace Contoso.Orders;

public static class OrderDefaults
{
    public static TimeSpan PaymentTimeout { get; set; } = TimeSpan.FromSeconds(30); // public static setter
}

Why: A public static setter lets any caller change process-wide state: every thread and every instance sees the change, and tests that set it leak into later tests. A get-only static auto-property can be assigned only by its initializer or the static constructor, so the value is fixed for the life of the process once the type is initialized. Declare the property as an auto-property; a private static field that a get-only property only returns is a trivial backing field, which IDE0032 reports (VAR-520).

Exceptions: State that must change at run time stays in a private static field that only methods change, and those methods make the update thread-safe (VAR-513, ASYNC-021). Settings that differ per deployment come from configuration injected into the type that needs them, not from a static property.

See also: VAR-513 (static fields), VAR-527 (reading static members), ASYNC-021 (thread safety).

Scope: Static properties and static state shared across instances · Enforced: Manual · Sources: MS-FDG-PROPERTY, MS-CA, AV

Arrays and collections

These rules cover how to create, populate, expose and index arrays and collections.

VAR-530

DO declare arrays as T[], create them with collection expressions (int[] quantities = [1, 2, 3];), and use jagged arrays (T[][]) instead of multidimensional arrays (T[,]) in public APIs.

C# 12: Collection expressions need C# 12. With a LangVersion below 12, create arrays with new[] { 1, 2, 3 }; the other parts of this rule do not change.

✅ Correct

private readonly int[] _quantities = [1, 2, 3]; // collection expression

public int TotalQuantity => _quantities.Sum();

public static int[][] CreateSeatMap(int rows, int seatsPerRow) =>
    [.. Enumerable.Range(0, rows).Select(_ => new int[seatsPerRow])];

❌ Incorrect — array initializer, and a multidimensional array in a public API

namespace Contoso.Orders;

public static class SeatPlanner
{
    private static readonly int[] DefaultRows = new int[] { 10, 12, 14 }; // not a collection expression

    public static int[,] CreateSeats(int rows, int columns) => new int[rows, columns]; // multidimensional array

    public static int DefaultRowCount => DefaultRows.Length;
}

Why: One bracket syntax creates arrays, lists and spans, and the compiler picks the cheapest construction for the target type. Multidimensional arrays (T[,]) are slower to index than jagged arrays in the runtime, do not implement IEnumerable<T> (so LINQ does not apply to them directly), and force every row to the same length. IDE0300 reports new T[] { ... } creation, and CA1814 reports members declared as multidimensional arrays.

Exceptions: Create a sized array with new int[count] when the elements are filled later; there is no collection expression for that. A multidimensional array is acceptable inside one method when it models a fixed rectangular grid that never leaves the method.

Scope: Array declarations and array creation · Enforced: IDE0300, CA1814 · Config: dotnet_style_prefer_collection_expression · Sources: MS-CONV, MS-CA, MS-FDG-PARAMDESIGN, MS-LANG-12

VAR-531

DO create a list, set, queue or stack with a collection expression (List<OrderLine> lines = [first, second];, [..existing, extra]), passing a capacity or comparer through the constructor only when one is needed.

C# 12: Collection expressions and the spread element .. need C# 12. With a LangVersion below 12, use a collection initializer (new List<OrderLine> { first, second }) and AddRange.

✅ Correct

private readonly List<string> _skus = ["SKU-1", "SKU-2"]; // collection expression

private readonly HashSet<string> _seenSkus = new(StringComparer.Ordinal); // comparer needed, so constructor

public IReadOnlyList<string> GetSkusWithExtra() => [.. _skus, "SKU-3"]; // spread

public bool MarkSeen(string sku) => _seenSkus.Add(sku);

❌ Incorrect — collection initializer instead of a collection expression

private readonly List<string> _skus = new List<string> { "SKU-1", "SKU-2" }; // collection initializer

public int SkuCount => _skus.Count;

Why: A collection expression replaces new List<T> { ... }, AddRange and Concat with one syntax, and the spread element copies another collection in place. The compiler can size the list up front. A collection expression for a loosely matching target type, such as an interface, can change the runtime type.

Exceptions: The rule applies when the declared type is the created type. A target typed as an interface (IList<T>) keeps its explicit creation, because a loose match can change the runtime type. A collection that needs a comparer or capacity is created with new(...).

See also: VAR-014 (target-typed new()), VAR-533 (dictionaries).

Scope: Lists, sets, queues, stacks and other collection types with an Add method · Enforced: IDE0028, IDE0303, IDE0304, IDE0306, ReSharper: UseCollectionExpression · Config: dotnet_style_prefer_collection_expression, dotnet_style_collection_initializer, resharper_use_collection_expression_highlighting · Sources: MS-CONV, MS-IDE, MS-LANG-12, AV

VAR-532

DO write an empty collection as [] wherever the target type allows it, instead of new T[0], Array.Empty<T>(), Enumerable.Empty<T>() or new List<T>().

C# 12: [] is a collection expression and needs C# 12. With a LangVersion below 12, use Array.Empty<T>() for arrays and new List<T>() for lists.

✅ Correct

public static IReadOnlyList<OrderLine> GetEmptyLines() => []; // empty collection expression

❌ Incorrect — Array.Empty<T>() instead of []

public static OrderLine[] GetEmptyLines() => Array.Empty<OrderLine>(); // empty collection not written as []

Why: [] is one spelling for every empty collection, and the compiler uses a shared empty instance where the target type allows it (for arrays, the same cached instance that Array.Empty<T>() returns). Collection expressions replace Array.Empty<T>().

Exceptions: var and other untyped contexts cannot take [] because there is no target type; give the variable its type.

Scope: Empty collections and arrays · Enforced: IDE0301, CA1825 · Sources: MS-CA, MS-IDE

VAR-533

DO populate a dictionary with an index initializer (["SKU-1"] = 9.99m) and pass a StringComparer (usually StringComparer.Ordinal or OrdinalIgnoreCase) whenever the key is a string.

✅ Correct

private readonly Dictionary<string, decimal> _prices = new(StringComparer.Ordinal) // comparer for string keys
{
    ["SKU-1"] = 9.99m,
    ["SKU-2"] = 19.99m
};

public bool TryGetPrice(string sku, out decimal price) => _prices.TryGetValue(sku, out price);

❌ Incorrect — Add-style entries and no comparer

private readonly Dictionary<string, decimal> _prices = new() // string keys without a StringComparer
{
    { "SKU-1", 9.99m }, // Add-style entry
    { "SKU-2", 19.99m } // Add-style entry
};

public bool TryGetPrice(string sku, out decimal price) => _prices.TryGetValue(sku, out price);

Why: An index initializer reads as key = value, the same as an assignment to _prices["SKU-1"]. A string-keyed dictionary uses ordinal comparison by default, but the declaration does not say so; naming StringComparer.Ordinal states the intent, and OrdinalIgnoreCase can only be had by passing it. C# 14 has no collection expressions for dictionaries, so the index initializer is the shortest form.

Exceptions: A dictionary whose keys are not strings needs no comparer unless the key type defines its own equality rules.

See also: LANG-041 (explicit string comparison), VAR-531 (other collections).

Scope: Dictionaries and other keyed collections · Enforced: Manual · Sources: MS-STR, AV

VAR-534

DO store data that never changes after construction in an immutable or frozen collection (ImmutableArray<T>, FrozenSet<T>, FrozenDictionary<TKey, TValue>), created with a collection expression or a ToFrozenSet, ToFrozenDictionary or ToImmutable... call.

C# 12: Collection expressions for ImmutableArray<T> rely on collection builders, which need C# 12 and .NET 8 or later. Below that, use ImmutableArray.Create(...).

✅ Correct

using System.Collections.Frozen;
using System.Collections.Immutable;

namespace Contoso.Orders;

public static class ShippingCatalogue
{
    private static readonly ImmutableArray<string> Carriers = ["Contoso Express", "Contoso Freight"];

    private static readonly FrozenSet<string> CarrierSet = Carriers.ToFrozenSet(StringComparer.Ordinal);

    public static bool IsKnown(string carrier) => CarrierSet.Contains(carrier);
}

❌ Incorrect — ImmutableArray.Create instead of a collection expression

using System.Collections.Immutable;

namespace Contoso.Orders;

public static class ShippingCatalogue
{
    private static readonly ImmutableArray<string> Carriers =
        ImmutableArray.Create("Contoso Express", "Contoso Freight"); // Create call instead of collection expression

    public static int CarrierCount => Carriers.Length;
}

Why: The type states that the data cannot change, so no caller can modify a shared table by mistake and no lock is needed to read it. Frozen collections (FrozenSet<T>, FrozenDictionary<TKey, TValue>) cost more to create than a Dictionary<TKey, TValue> and read faster, so build them once, in a static readonly field, and read them many times.

Exceptions: When the elements are computed at run time, ToImmutableArray() or ToFrozenSet() is the right call; a collection expression is for literal elements.

Scope: Collections that never change after construction · Enforced: IDE0303, IDE0304 · Sources: MS-IDE, MS-CA, AV

VAR-535

DO expose collections from public members as IReadOnlyList<T>, IReadOnlyCollection<T>, IReadOnlyDictionary<TKey, TValue> or, for lazily produced sequences, IEnumerable<T>, never as List<T> or as a settable collection property.

✅ Correct

namespace Contoso.Orders;

public sealed class OrderHistory(IReadOnlyList<Order> orders)
{
    public IReadOnlyList<Order> Orders { get; } = orders; // read-only interface, no setter
}

❌ Incorrect — List<T> in a public API, and a settable collection property

namespace Contoso.Orders;

public sealed class OrderHistory
{
    public static List<Order> GetOrders() => []; // List<T> in a public API

    public List<Order> Orders { get; set; } = []; // settable collection property
}

Why: A List<T> in a public signature lets every caller add, remove and reorder items, and ties the API to one implementation. The read-only interfaces say what callers may do. A settable collection property (List<Order> Orders { get; set; }, CA2227) additionally lets callers replace the whole collection. Return an empty collection, never null (TYPE-024). The 2008 Framework Design Guidelines name Collection<T> and ReadOnlyCollection<T> for this purpose; these types predate the read-only interfaces.

Exceptions: Private and internal members may use List<T>; CA1002 and CA2227 look at externally visible members only.

See also: TYPE-024 (never return null for a collection).

Scope: Return types, property types and parameter types of public members that carry collections · Enforced: CA1002, CA2227 · Sources: MS-FDG-COLL, MS-CA, AV

VAR-536

CONSIDER use the index operator ^ and the range operator .. (lines[^1], sku[4..]) instead of Length - 1 arithmetic and Substring or Slice calls.

✅ Correct

public static OrderLine GetLastLine(OrderLine[] lines) => lines[^1]; // index from the end

public static string GetSkuNumber(string sku) => sku[4..]; // range to the end

❌ Incorrect — length arithmetic and Substring

public static OrderLine GetLastLine(OrderLine[] lines) => lines[lines.Length - 1]; // length arithmetic

public static string GetSkuNumber(string sku) => sku.Substring(4, sku.Length - 4); // Substring instead of range

Why: ^1 counts from the end and names lines once, so the off-by-one error in Length - 1 cannot occur, and sku[4..] removes the repeated sku.Length. Both IDE rules ship at suggestion, which dotnet build does not report; the IDE shows them, and you can raise them to warning in your own configuration.

Exceptions: Keep Substring(start, length) when the length is a named value that is not derived from the end, because [start..(start + length)] is not clearer. A range on an array copies the elements; in a hot loop slice with AsSpan(range) instead.

Scope: Index and slice expressions on arrays, spans and strings · Enforced: IDE0056, IDE0057 · Config: csharp_style_prefer_index_operator, csharp_style_prefer_range_operator · Sources: MS-IDE

Tuples, records and special types

These rules cover tuples, records, structs, anonymous types, dynamic and object, enums, delegates and generic constraints.

VAR-540

DO write tuple types with the tuple syntax and named elements ((int Count, decimal Total)), read elements by name, and never use Tuple<T1, T2> or ValueTuple<T1, T2> spelled out.

✅ Correct

public static (int Count, decimal Total) Summarize(Order order) => (order.Lines.Count, order.Total);

public static decimal GetTotal(Order order) => Summarize(order).Total; // element read by name

❌ Incorrect — elements read by position, and Tuple<T1, T2>

(int Count, decimal Total) summary = (3, 9.99m);
decimal total = summary.Item2; // element read by position
Tuple<int, decimal> pair = Tuple.Create(3, 9.99m); // Tuple<T1, T2> instead of tuple syntax

Why: Total says what the element is and Item2 does not, and a rename of the tuple's elements is caught by the compiler. Tuple<T1, T2> is a reference type that allocates and has no element names; the tuple syntax is the ValueTuple struct with names.

Exceptions: A tuple that crosses a public boundary and that callers store is better as a record (VAR-542, TYPE-020).

See also: NAM-234 (tuple element names).

Scope: Tuple types and tuple element access · Enforced: IDE0033 · Config: dotnet_style_explicit_tuple_names · Sources: MS-IDE, SA, AV, GOOG

VAR-541

DO deconstruct a tuple or record into separately declared locals (var (count, total) = Summarize(order);) instead of keeping a tuple local and reading its elements.

✅ Correct

private static (int Count, decimal Total) Summarize(Order order) => (order.Lines.Count, order.Total);

public static decimal CalculateAveragePrice(Order order)
{
    var (count, total) = Summarize(order); // one local per element

    return count == 0 ? 0m : total / count;
}

✅ Accepted — explicit types

private static (int Count, decimal Total) Summarize(Order order) => (order.Lines.Count, order.Total);

public static decimal CalculateAveragePrice(Order order)
{
    (int count, decimal total) = Summarize(order);

    return count == 0 ? 0m : total / count;
}

❌ Incorrect — tuple local whose elements are only read

(int Count, decimal Total) summary = (3, 9.99m); // tuple local whose elements are only read
decimal average = summary.Total / summary.Count;

Why: Deconstruction gives each element its own local with its own name, so later code reads total instead of summary.Total. var (count, total) is the form VAR-010 prefers: the element types come from the return type of Summarize, so the line does not repeat them. Writing the types ((int count, decimal total)) is accepted.

Exceptions: Keep the tuple as one value when you pass it on unchanged to another method or return it.

See also: NAM-235 (names of deconstructed variables), VAR-010 (var for locals).

Scope: Deconstruction of tuples, records and types with Deconstruct · Enforced: IDE0042, ReSharper: ArrangeVarKeywordsInDeconstructingDeclaration · Config: csharp_style_deconstructed_variable_declaration, resharper_csharp_prefer_separate_deconstructed_variables_declaration, resharper_arrange_var_keywords_in_deconstructing_declaration_highlighting · Sources: MS-IDE, AV, RS-SYNTAX

VAR-542

DO declare a reference record with the record keyword (not record class), use positional syntax only for small immutable data, and use a nominal record with required or init properties when it has more than about four members.

✅ Correct

namespace Contoso.Orders;

public sealed record OrderLineAdded(int OrderId, string Sku, int Quantity); // small, immutable: positional

public sealed record CustomerProfile
{
    public required int CustomerId { get; init; }

    public required string DisplayName { get; init; }

    public string? Email { get; init; }
}

❌ Incorrect — redundant class keyword, and a long positional record

namespace Contoso.Orders;

public sealed record class OrderLineAdded(int OrderId, string Sku, int Quantity); // redundant class keyword

public sealed record ShipmentRequested( // too many positional members
    int OrderId,
    string Carrier,
    string Street,
    string City,
    string PostalCode,
    bool Insured);

Why: record already means a reference type, so record class adds a word and no meaning. Positional parameters become public init properties in declaration order, and a call such as new ShipmentRequested(7, "Contoso Express", ...) with six arguments of similar shape cannot be read without the declaration; a nominal record names each value at the call site and required makes the compiler check them.

Exceptions: record struct and readonly record struct are the value-type forms (VAR-543).

See also: TYPE-020 (choosing a record, class or struct), NAM-221 (positional record parameters are PascalCase).

Scope: Record declarations (choosing between record, class and struct: TYPE-020) · Enforced: Manual · Sources: MS-CONV, AV

VAR-543

DO declare a struct that represents a value readonly (readonly struct, readonly record struct) and mark every member of a mutable struct that does not change state readonly.

✅ Correct

namespace Contoso.Orders;

public readonly record struct Money(decimal Amount, string Currency);

public readonly struct Percentage(decimal value) // readonly: the value never changes
{
    public decimal Value { get; } = value;
}

✅ Correct — struct enumerator: mutable, with a readonly member

namespace Contoso.Orders;

public struct LineEnumerator(OrderLine[] lines)
{
    private int _index = -1;

    public readonly OrderLine Current => lines[_index]; // does not change state, so readonly

    public bool MoveNext()
    {
        _index++;

        return _index < lines.Length;
    }
}

❌ Incorrect — struct and member not marked readonly

namespace Contoso.Orders;

public struct Percentage(decimal value) // value struct not marked readonly
{
    public decimal Value { get; } = value;
}

public struct LineEnumerator(OrderLine[] lines)
{
    private int _index = -1;

    public OrderLine Current => lines[_index]; // non-mutating member not marked readonly

    public bool MoveNext()
    {
        _index++;

        return _index < lines.Length;
    }
}

Why: A readonly struct cannot change after construction, so the compiler can pass it by in reference without defensive copies. Calling a non-readonly member on a readonly field or an in parameter makes the compiler copy the struct first; marking the member readonly avoids that copy and documents that it does not change state.

Exceptions: A mutable struct is allowed only as an enumerator or a ref-struct cursor (TYPE-020); mark its members that do not change state readonly, as Current is above. Choosing a struct at all is covered by TYPE-020.

Scope: Structs and record structs · Enforced: IDE0250, IDE0251 · Config: csharp_style_prefer_readonly_struct, csharp_style_prefer_readonly_struct_member · Sources: MS-FDG-CLASSSTRUCT, MS-IDE

VAR-544

DO use an anonymous type only for a projection that stays inside one method, and use a named record when the data is returned, stored in a field or passed to another method.

✅ Correct

public static int FindLargestOrderId(IEnumerable<Order> orders)
{
    var largest = orders.Select(order => new { order.Id, order.Total }).MaxBy(item => item.Total);

    return largest?.Id ?? 0; // only an int leaves the method, the anonymous type does not
}

❌ Incorrect — anonymous type returned as object

public static object Summarize(Order order) => new { order.Id, order.Total }; // anonymous type escapes as object

Why: An anonymous type has no name, so once it leaves the method the caller sees object and cannot read Id or Total without reflection or dynamic. A named record has the same shape, equality and ToString, and every caller can use it. The var is required here because the type has no name (VAR-010).

Exceptions: A LINQ query or a lambda that uses the projection and returns a plain value, as above, is the intended use.

See also: VAR-542 (named records), NAM-240 (anonymous-type member names).

Scope: Anonymous types · Enforced: Manual · Sources: MS-CONV, AV

VAR-545

DO NOT declare a variable, parameter or return type as dynamic except for COM or dynamic-language interop, or as object where a generic type parameter or a specific type expresses the same thing.

✅ Correct

public static T GetFirstOrFallback<T>(IReadOnlyList<T> items, T fallback) =>
    items.Count > 0 ? items[0] : fallback; // one type parameter, no casts

❌ Incorrect — dynamic and object where a type or type parameter fits

public static dynamic GetOrderId(Order order) => order.Id; // dynamic for ordinary data

public static object GetFirstOrFallback(IReadOnlyList<object> items, object fallback) => // object instead of a type parameter
    items.Count > 0 ? items[0] : fallback;

Why: dynamic moves member lookup to run time, so a misspelled member compiles and fails in production, and the editor cannot complete or check it. object forces a cast at every call and boxes value types; a type parameter keeps the caller's type and removes the cast.

Exceptions: dynamic is allowed for COM automation and for dynamic-language interop. A member that overrides or implements a signature declared on object (Equals(object?)) keeps object.

Scope: dynamic and object as declared types · Enforced: Manual · Sources: MS-CONV, AV

VAR-546

DO keep int as the underlying type of an enum unless interop or a storage format needs another type, give the zero value a meaning (None, Unknown or the natural default), and assign an explicit value to every member that is persisted or sent between systems.

✅ Correct

namespace Contoso.Orders;

public enum ReturnReason
{
    Unknown = 0, // zero is the default value, so it means "not set"
    Damaged = 1,
    WrongItem = 2
}

❌ Incorrect — non-int underlying type

namespace Contoso.Orders;

public enum ReturnReason : byte // non-int underlying type
{
    Unknown = 0,
    Damaged = 1,
    WrongItem = 2
}

Why: int is the default and needs no conversion at the call sites; a byte enum saves three bytes per stored value and nothing else. A field of an enum type starts as zero, so zero must be a member that means "not set" or the natural default (CA1008 reports an enum without a zero member). Explicit numbers on persisted members keep stored and transmitted values stable when someone inserts or reorders members.

Exceptions: Use another underlying type when an interop signature or a file or wire format fixes the width (byte for a one-byte protocol field, ulong for a [Flags] enum with more than 32 flags).

See also: NAM-120 (enum names), NAM-121 ([Flags] enums), TYPE-020.

Scope: Enum declarations (naming: NAM-120, NAM-121) · Enforced: CA1028, CA1008 · Sources: MS-FDG-ENUM, MS-CA, SA

VAR-547

CONSIDER typing delegate variables and parameters as Func<> or Action<>, and marking a lambda that captures nothing static.

✅ Correct

public static IEnumerable<decimal> SelectTotals(IEnumerable<Order> orders, Func<Order, decimal> selector) =>
    orders.Select(selector); // Func<> instead of a custom delegate

public static IEnumerable<decimal> SelectOrderTotals(IEnumerable<Order> orders) =>
    SelectTotals(orders, static order => order.Total); // static: captures nothing

❌ Incorrect — custom delegate type, and a lambda that captures nothing but is not static

public delegate decimal OrderSelector(Order order); // custom delegate where Func fits

public static IEnumerable<decimal> SelectTotals(IEnumerable<Order> orders, OrderSelector selector) =>
    orders.Select(order => selector(order));

public static IEnumerable<decimal> SelectOrderTotals(IEnumerable<Order> orders) =>
    SelectTotals(orders, order => order.Total); // lambda captures nothing but is not static

Why: Every reader knows Func<Order, decimal>, and it converts to and from the delegates that LINQ and the BCL already use; two delegate types with the same signature do not convert to each other. A static lambda cannot capture a local or this, so the compiler rejects an accidental capture that would allocate a closure. IDE0320 ships at suggestion, which dotnet build does not report, and the Func/Action part has no diagnostic at all, so reviewers check both halves.

Exceptions: Declare a custom delegate when the signature needs ref, out, in or params parameters, which Func<> cannot express, or when a public callback type deserves a name of its own.

Scope: Delegate-typed variables, parameters and lambdas · Enforced: IDE0320 · Config: csharp_prefer_static_anonymous_function · Sources: MS-CONV, MS-IDE, AV

VAR-548

DO add to each type parameter exactly the constraints the generic code needs (where T : notnull, class, struct, an interface or new()), and no constraint the code does not use.

✅ Correct

namespace Contoso.Orders;

public sealed class OrderCache<TKey, TValue>
    where TKey : notnull // Dictionary needs a non-null key
{
    private readonly Dictionary<TKey, TValue> _items = [];

    public void Set(TKey key, TValue value) => _items[key] = value;

    public TValue? Find(TKey key) => _items.GetValueOrDefault(key);
}

❌ Incorrect — missing and unused constraints

namespace Contoso.Orders;

public sealed class OrderCache<TKey, TValue> // TKey lacks the notnull constraint the dictionary needs
    where TValue : class, new() // constraints the code never uses
{
    private readonly Dictionary<TKey, TValue> _items = [];

    public void Set(TKey key, TValue value) => _items[key] = value;
}

Why: A constraint is a promise that every caller must keep. A missing constraint pushes the problem into the body (a nullable warning, CS8714, or a ! on the key), and an unused one rejects valid arguments: new() excludes abstract types and types without a public parameterless constructor, and class excludes structs. Since C# 13 the allows ref struct anti-constraint belongs here too; add it only when the code compiles with it, because the compiler rejects boxing or storing such a type argument.

Scope: Generic type parameters and their constraints · Enforced: Manual · Sources: MS-FDG-TYPES, AV, MS-LANG-13

Declaration forms

These rules cover out variables, using declarations, patterns, ref locals, spans, shadowing and loop-counter capture.

VAR-550

DO declare an out variable inline at the call (out var quantity; an explicit type is accepted) and pass out _ for a result you do not need.

✅ Correct

public static int ParseQuantity(string text)
{
    return int.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out var quantity) ? quantity : 0;
}

public static bool IsNumeric(string text) =>
    int.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out _); // result not needed

❌ Incorrect — variable declared before the call

public static int ParseQuantity(string text)
{
    int quantity; // declared before the call
    if (int.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out quantity))
    {
        return quantity;
    }

    return 0;
}

Why: The inline declaration puts the variable, its type and the only assignment in one place, and the variable cannot be read above the call that sets it. out _ states that the result is ignored on purpose. out var quantity takes its type from the parameter of the method, so the call does not repeat it, which is the form VAR-010 prefers; out int quantity is accepted.

See also: NAM-233 (discards).

Scope: out arguments · Enforced: IDE0018, ReSharper: InlineOutVariableDeclaration · Config: csharp_style_inlined_variable_declaration, resharper_inline_out_variable_declaration_highlighting · Sources: MS-IDE, RT-EC, RS-INSPECT

VAR-551

DO declare a disposable resource with a using declaration (using var stream = File.OpenRead(path);) unless it must be released before the end of the enclosing block, in which case use a using block.

✅ Correct

public static long GetExportSize(string path)
{
    using var stream = File.OpenRead(path); // disposed at the end of the method

    return stream.Length;
}

✅ Accepted — explicit type

public static long GetExportSize(string path)
{
    using FileStream stream = File.OpenRead(path);

    return stream.Length;
}

❌ Incorrect — using block where a declaration fits

public static long GetExportSize(string path)
{
    using (var stream = File.OpenRead(path)) // block where a declaration fits
    {
        return stream.Length;
    }
}

Why: A using declaration disposes the resource when the enclosing block ends, as the block form does, without the extra nesting level. Early returns and exceptions still dispose it. The type comes from File.OpenRead, so var (VAR-010) does not repeat it; the explicit FileStream is accepted.

Exceptions: Use a using block when the resource must be released before the end of the enclosing block, for example to close a file before a later step in the same method reads it.

See also: ERR-020 (dispose what you own), NAM-238 (names of using variables).

Scope: using statements for disposable resources · Enforced: IDE0063, ReSharper: ConvertToUsingDeclaration · Config: csharp_prefer_simple_using_statement, resharper_convert_to_using_declaration_highlighting · Sources: MS-CONV, MS-IDE, RS-INSPECT

VAR-552

DO release a resource that implements IAsyncDisposable with await using (await using FileStream stream = ...;).

✅ Correct

public static async Task<long> CopyAsync(Stream source, string path, CancellationToken cancellationToken = default)
{
    await using FileStream target = File.Create(path); // asynchronous disposal
    await source.CopyToAsync(target, cancellationToken);

    return target.Length;
}

❌ Incorrect — using on an async-disposable resource (reported by Rider and ReSharper only)

public static async Task<long> CopyAsync(Stream source, string path, CancellationToken cancellationToken = default)
{
    using FileStream target = File.Create(path); // synchronous dispose of an async-disposable resource
    await source.CopyToAsync(target, cancellationToken);

    return target.Length;
}

Why: Disposing a FileStream flushes its buffer. Dispose() does that on the calling thread and blocks it, while DisposeAsync() flushes asynchronously, so an async method should use it. No Roslyn diagnostic asks for await using, so the build does not fail; Rider and ReSharper highlight the synchronous using.

Exceptions: A type that implements only IDisposable uses using. A synchronous method cannot use await using.

See also: ERR-020 (dispose what you own).

Scope: Resources that implement IAsyncDisposable · Enforced: ReSharper: UseAwaitUsing · Config: resharper_use_await_using_highlighting · Sources: MS-ASYNCRET, RS-INSPECT

VAR-553

DO use relational (< 0), logical (and, or, not) and extended property patterns ({ Lines.Count: 0 }) instead of chained == comparisons, !(x is T) and nested property patterns.

✅ Correct

public static bool IsOpen(OrderStatus status) => status is OrderStatus.Pending or OrderStatus.Paid; // logical pattern

public static bool IsNotCard(Payment payment) => payment is not CardPayment;

public static bool IsValidDiscount(decimal percentage) => percentage is > 0m and <= 100m;

public static bool IsEmpty(Order order) => order is { Lines.Count: 0 }; // extended property pattern

❌ Incorrect — chained comparisons, negated is and a nested property pattern

public static bool IsOpen(OrderStatus status) =>
    status == OrderStatus.Pending || status == OrderStatus.Paid; // chained comparisons

public static bool IsNotCard(Payment payment) => !(payment is CardPayment); // negated is

public static bool IsUnpaid(Order order) => !(order.Status is OrderStatus.Paid); // negated is

public static bool IsEmpty(Order order) => order is { Lines: { Count: 0 } }; // nested property pattern

Why: A pattern names the tested value once, so status is A or B cannot compare two different variables by typing error. is not avoids the parentheses and the easily missed leading !, and an extended property pattern removes one pair of braces per level.

Exceptions: A chain that compares different variables (width == 0 || height == 0) is not a pattern case. To test the shape of a sequence, use a list pattern instead of Length or Count checks and indexing: lines is [{ Quantity: > 0 }, ..] is true when the array has a first line with a positive quantity.

See also: LANG-020 (declaration patterns instead of as and casts).

Scope: Pattern-matching declarations and conditions · Enforced: IDE0078, IDE0083, IDE0170 · Config: csharp_style_prefer_pattern_matching, csharp_style_prefer_not_pattern, csharp_style_prefer_extended_property_pattern · Sources: MS-IDE, AV, MS-CONV

VAR-554

DO use ref locals, ref returns and scoped only on a measured hot path to avoid copying large structs, and prefer ref readonly when the caller must not write through the reference.

✅ Correct

namespace Contoso.Orders;

public readonly record struct Money(decimal Amount, string Currency);

public static class MoneyMath
{
    public static decimal GetFirstAmount(ReadOnlySpan<Money> amounts)
    {
        // Measured in PricingBenchmarks.SumLines: avoids copying Money in the pricing loop.
        ref readonly Money first = ref amounts[0];

        return first.Amount;
    }
}

❌ Incorrect — ref local without a measured need

namespace Contoso.Orders;

public readonly record struct Money(decimal Amount, string Currency);

public static class MoneyMath
{
    public static decimal GetFirstAmount(Span<Money> amounts)
    {
        ref Money first = ref amounts[0]; // ref used without a measured need

        return first.Amount;
    }
}

Why: A ref local is an alias for the original storage, so a write through it changes the original, and its lifetime rules (scoped, ref returns) are harder to read than a plain copy. A ref local cannot stay live across await or yield. Use the feature where a benchmark shows that the copy costs something, name the benchmark in a comment, and use ref readonly so the alias cannot write.

Exceptions: A ref local to update a struct in place inside an array or list is legitimate when the update is the purpose; the rule is about avoiding copies without evidence.

Scope: ref locals, ref returns, ref readonly and scoped · Enforced: Manual · Sources: MS-LANG-12, MS-LANG-13, GOOG

VAR-555

DO slice and buffer data with Span<T> and ReadOnlySpan<T> instead of pointers and unsafe code, and use stackalloc only with a small constant size and never inside a loop.

✅ Correct

public static string NormalizeSku(ReadOnlySpan<char> sku)
{
    Span<char> buffer = stackalloc char[16]; // constant size, outside any loop
    int written = sku.ToUpperInvariant(buffer);

    return written < 0 ? sku.ToString().ToUpperInvariant() : new string(buffer[..written]);
}

❌ Incorrect — stackalloc inside a loop

public static int CalculateTotalLength(IEnumerable<string> skus)
{
    int total = 0;
    foreach (string sku in skus)
    {
        Span<char> buffer = stackalloc char[16]; // stackalloc inside a loop
        total += sku.AsSpan().ToUpperInvariant(buffer);
    }

    return total;
}

Why: A Span<T> is a bounds-checked view over an array, a string or stack memory, so slicing needs no copy and no unsafe pointer arithmetic that can read past the end. Stack memory from stackalloc is released only when the method returns, so inside a loop every pass takes more stack until the process fails with a stack overflow, which cannot be caught. The example buffer is 16 char (32 bytes); for a size that depends on the input, rent from ArrayPool<T> instead.

Exceptions: Use pointers and unsafe code only where a native interop signature requires them.

Scope: Span<T>, ReadOnlySpan<T>, stackalloc and unsafe code · Enforced: CA2014 · Sources: MS-CA, MS-IDE, MS-LANG-12

VAR-556

DO NOT declare a local, parameter or lambda parameter with the name of a field, property or outer local that is in scope.

✅ Correct

public int LineCount { get; private set; }

public void AddLines(int additionalLines) // distinct from the property LineCount
{
    LineCount += additionalLines;
}

❌ Incorrect — lambda parameter that hides an outer local

public static decimal FindLargestAmount(IReadOnlyList<OrderLine> lines)
{
    OrderLine line = lines[0];

    return lines.Max(line => line.Amount) - line.Amount; // lambda parameter hides the local line
}

Why: Two things with one name in one scope make the name ambiguous to the reader: in the incorrect example the two line.Amount expressions mean different things. A nested block's local that reuses an outer local's name is error CS0136, but since C# 8 a lambda or local-function parameter may shadow an outer local, and shadowing a member never produces a diagnostic, so reviewers check both. With the naming rules in place (_lines, lineCount, LineCount) a correctly named local or parameter cannot collide with a field or property; a local named Total in a class with a Total property is reported by IDE1006 as a casing error, not as shadowing.

See also: NAM-230 (local names), NAM-220 (parameter names).

Scope: Locals, parameters and lambda parameters · Enforced: Manual · Sources: AV, MS-IDNAME

VAR-557

DO NOT capture the counter of a for loop in a lambda or local function; copy it to a local declared inside the loop body and capture that local.

✅ Correct

public static IReadOnlyList<Func<int>> CreateReaders(int count)
{
    List<Func<int>> readers = [];
    for (int i = 0; i < count; i++)
    {
        int lineIndex = i; // one new variable per iteration
        readers.Add(() => lineIndex);
    }

    return readers;
}

❌ Incorrect — lambda captures the loop counter

public static IReadOnlyList<Func<int>> CreateReaders(int count)
{
    List<Func<int>> readers = [];
    for (int i = 0; i < count; i++)
    {
        readers.Add(() => i); // every lambda sees the final counter value
    }

    return readers;
}

Why: A for loop declares one counter for the whole loop, so every lambda that captures i reads the same variable, and after the loop each lambda returns count. A local declared inside the body is a new variable on every pass, so each lambda keeps its own value.

Exceptions: A foreach iteration variable can be captured directly, because each iteration has its own copy of it.

Scope: Loop variables used inside lambdas and local functions · Enforced: Manual · Sources: MS-CONV, AV

Sources

The keys cited in this chapter are listed on the Sources page.

MS-FDG-FIELD, MS-FDG-PROPERTY, MS-FDG-COLL, MS-FDG-PARAMDESIGN, MS-FDG-CLASSSTRUCT, MS-FDG-ENUM, MS-FDG-TYPES, MS-CA, MS-CONV, MS-IDE, MS-IDE-OPTIONS, MS-IDNAME, MS-NRT, MS-STR, MS-ASYNCRET, MS-LANG-12, MS-LANG-13, MS-LANG-14, RT-STYLE, RT-EC, RS-INSPECT, RS-BODIES, RS-SYNTAX, SA, AV, GOOG.

Previous: Variables: Types, Literals and Nullability · Home · Next: Language Features