Skip to content

Variables: Types, Literals and Nullability

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

Home · Rule index · Naming cheat sheet

This chapter covers how to declare a local variable and how to write a value of a given type. It sets when a local uses var and when it uses an explicit type, which built-in type holds which kind of value, how to write numeric and string literals, which types hold dates, times and durations, and how to mark a value as nullable. The examples are application code in the Contoso.Orders domain.

Naming a field or property is covered in page 03 and page 04. Declaring it (const vs static readonly, readonly, initialisation) is covered in page 06.

The var policy in one line: declare locals with var, and write the explicit type where the type matters more than the name or where a literal would give the wrong type; an explicit type is always accepted. The table shows what to write for each kind of value and links the rule that applies.

You declare Write Rule
A local created with new, a cast or an anonymous type var order = new Order(7, createdAt); VAR-010
A local of a built-in type var lineCount = 0;, var unitPrice = 9.99m; VAR-010, VAR-020
A local filled by a method call, property, await or LINQ query var order = await repository.GetAsync(orderId, cancellationToken); VAR-010
A loop variable foreach (var line in order.Lines) VAR-010
A field or property initialized with its own type private readonly StringBuilder _summary = new(); VAR-014
A default value OrderStatus status = default; VAR-015
A whole number, a price, a measurement int, decimal unitPrice = 9.99m;, double weightInKilograms VAR-021, VAR-022, VAR-024
Text "Shipped", a raw string literal for quotes and lines, "" for empty, $"Order {order.Id}" VAR-030, VAR-032, VAR-033
A moment, a date, a time of day, a duration DateTimeOffset, DateOnly, TimeOnly, TimeSpan VAR-040 to VAR-043
A value that can be missing Order?, int? VAR-051, VAR-052
A constant const int MaxLinesPerOrder = 50; VAR-510 (page 06)
A collection, a tuple, an out variable, a using resource List<OrderLine> lines = [];, (int Count, decimal Total), out var shippedAt VAR-531, VAR-540, VAR-550, VAR-551 (page 06)

Rules marked Manual in their metadata line are checked in review, not by a tool (manual rule); page 15 lists them in Manual review only. The nullable rules assume that every project sets <Nullable>enable</Nullable> (VAR-050).

Rule index

ID Level Rule Enforced
VAR-010 CONSIDER declare locals with var (var order = new Order(7, createdAt);, var lineCount = 0;, var order = await repository.GetAsync(orderId, cancellationToken);, foreach (var line in order.Lines)); an explicit type is accepted, and it is needed where the variable must have a base type or a literal would give the wrong type. IDE0007 (suggestion), ReSharper: SuggestVarOrType_BuiltInTypes, SuggestVarOrType_SimpleTypes, SuggestVarOrType_Elsewhere
VAR-014 DO write target-typed new() in a field or property initializer whose declared type is the type being created (private readonly StringBuilder _summary = new();); prefer var for locals (VAR-010) and collection expressions for collections (VAR-531). IDE0090, ReSharper: ArrangeObjectCreationWhenTypeEvident
VAR-015 DO write the default literal instead of default(T) wherever the compiler can infer the type (OrderStatus status = default;, return default;). IDE0034, ReSharper: ArrangeDefaultValueWhenTypeEvident
VAR-016 DO declare one variable per declaration statement and declare each local in the narrowest scope, directly before its first use. Manual
VAR-017 DO initialize a variable in its declaration with the value it needs and never assign it a value that is overwritten before it is read. IDE0059, ReSharper: JoinDeclarationAndInitializer
VAR-020 DO write the C# keyword (int, long, string, bool, object, nint, nuint) instead of the BCL type name (Int32, Int64, String, Boolean, Object, IntPtr, UIntPtr), including in member access such as string.Join and int.Parse. ReSharper: BuiltInTypeReferenceStyle
VAR-021 DO use int for integer values unless the value range, a native interop signature or a file or wire format needs long, short, byte or an unsigned type, and keep unsigned types out of public API signatures. Manual
VAR-022 DO write the L, U and UL suffixes in upper case and the m, f and d suffixes in lower case (10_000L, 42U, 9.99m, 1.5f). CS0078
VAR-023 DO separate digit groups of a numeric literal with five or more digits with _ (1_000_000, 0xFF_FF), and write bit masks and flag values with 0b or 0x prefixes. Manual
VAR-024 DO use decimal for monetary amounts and double for measured or scientific quantities, and compare double or float values against a tolerance instead of with == or !=. Manual
VAR-025 DO NOT compare a Boolean expression with true or false, or select true or false with the conditional operator; use the expression itself or its negation. IDE0100, IDE0075
VAR-026 DO use a char literal and the char overload of Contains, StartsWith, EndsWith, IndexOf, Split and StringBuilder.Append when the argument is a single character, and write the escape character as '\e'. CA1847, CA1865, CA1866, CA1867, CA1834
VAR-027 DO give every literal with a business meaning a named constant or configuration value (const int MaxLinesPerOrder = 50;), and keep inline only 0, 1, -1, "" and literals whose meaning the line states. Manual
VAR-030 DO write single-line text as a regular string literal and text that contains quotes, backslashes or several lines as a raw string literal ("""..."""), using $$""" when the text contains braces. ReSharper: UseRawString
VAR-031 AVOID verbatim strings (@"...") for new file paths, regular expressions and other backslash-heavy text; write them as raw string literals. Manual
VAR-032 DO write an empty string as "", not as string.Empty, and test for missing text with string.IsNullOrEmpty (LANG-042). Manual
VAR-033 DO build display text with an interpolated string whose holes are expressions and whose format specifiers sit in the hole ($"Order {order.Id} total {order.Total:N2}"), instead of string.Format with numbered placeholders or ToString calls inside the holes. IDE0071, ReSharper: UseStringInterpolation
VAR-034 DO write an interpolated string that contains backslashes, quotes or line breaks as an interpolated raw string literal ($"""...""" or $$"""..."""), never as a verbatim interpolated string ($@"..." or @$"..."). Manual
VAR-035 DO write a constant byte sequence that represents ASCII or UTF-8 text as a UTF-8 string literal ("ORD"u8) instead of a byte array of character codes. IDE0230, ReSharper: UseUtf8StringLiteral
VAR-040 DO use DateTimeOffset for a point in time, such as when an order was placed or shipped. Manual
VAR-041 DO read the current time from an injected TimeProvider (timeProvider.GetUtcNow()) or, where no provider is available, from DateTimeOffset.UtcNow, and never use DateTime.Now or DateTimeOffset.Now for values that are stored or compared. Manual
VAR-042 DO use DateOnly for a calendar date such as a delivery date or birthday and TimeOnly for a time of day such as an opening time. Manual
VAR-043 DO represent a duration as a TimeSpan (var paymentTimeout = TimeSpan.FromSeconds(30);) instead of an int or double number of milliseconds, seconds or minutes. Manual
VAR-044 DO take a TimeProvider as a dependency in every class whose behaviour depends on the current time, and use FakeTimeProvider or a fake of your own in tests. Manual
VAR-050 DO enable nullable reference types in every project (<Nullable>enable</Nullable>) and fix every nullable warning (CS86xx) instead of suppressing it. CS8600, CS8602, CS8604, CS8625
VAR-051 DO add ? to every reference-typed field, property, parameter, return type and type argument that can hold null, and to no other reference type. CS8603, CS8618
VAR-052 DO write a nullable value type with the ? suffix (int?, DateOnly?), never as Nullable<T>. Manual
VAR-053 AVOID the null-forgiving operator (!); use it only where a value is provably non-null but the compiler cannot see it, with a comment on the same line that says why. IDE0370
VAR-054 DO annotate a Try-pattern or guard method with nullable analysis attributes such as [NotNullWhen(true)], [MaybeNullWhen(false)] or [NotNull] so callers need no !. CS8602

Implicit and explicit typing

Five rules cover how a variable is declared and initialized. Locals are declared with var (VAR-010), and the explicit type stays accepted; fields and properties cannot use var and use target-typed new() (VAR-014).

VAR-010

CONSIDER declaring locals with var (var order = new Order(7, createdAt);, var lineCount = 0;, var order = await repository.GetAsync(orderId, cancellationToken);, foreach (var line in order.Lines)); an explicit type is accepted, and it is needed where the variable must have a base type or a literal would give the wrong type.

✅ Correct

public static async Task<string> DescribeOrderAsync(
    IOrderRepository repository,
    int orderId,
    CancellationToken cancellationToken = default)
{
    var order = await repository.GetAsync(orderId, cancellationToken); // method result
    var unitCount = 0; // int literal
    var total = 0m; // decimal literal: the suffix gives the type
    foreach (var line in order.Lines) // loop variable
    {
        unitCount += line.Quantity;
        total += line.Amount;
    }

    var timeout = TimeSpan.FromSeconds(30); // static factory of the same type

    return $"Order {order.Id}: {unitCount} units, {total:N2}, expires after {timeout}";
}

✅ Correct — the type is on the right-hand side

public static string DescribePayment(Payment payment, TimeProvider timeProvider)
{
    var order = new Order(7, timeProvider.GetUtcNow()); // new expression
    var card = (CardPayment)payment; // explicit cast
    var summary = new { order.Id, card.MaskedNumber }; // anonymous type

    return $"Order {summary.Id} paid with {summary.MaskedNumber}";
}

✅ Accepted — explicit types

public static async Task<string> DescribeOrderAsync(
    IOrderRepository repository,
    int orderId,
    CancellationToken cancellationToken = default)
{
    Order order = await repository.GetAsync(orderId, cancellationToken);
    int unitCount = 0;
    decimal total = 0m;
    foreach (OrderLine line in order.Lines)
    {
        unitCount += line.Quantity;
        total += line.Amount;
    }

    TimeSpan timeout = TimeSpan.FromSeconds(30);

    return $"Order {order.Id}: {unitCount} units, {total:N2}, expires after {timeout}";
}

❌ Incorrect — var with a literal whose default type is not the one needed

public static decimal PriceFor(int quantity)
{
    var unitPrice = 9.99; // a double literal, not a decimal
    decimal total = unitPrice * quantity; // Cannot implicitly convert type 'double' to 'decimal' (CS0266)

    return total;
}

Why: var removes the second copy of a type that the line already shows, keeps the declaration short when the type name is long (Dictionary<string, List<OrderLine>>), and follows a type change in the right-hand side without an edit on the left. The Microsoft coding conventions prefer var where the type is obvious from the right-hand side or unimportant, and use it for the counter of a for loop, but advise against it where the type is not apparent from the right-hand side, and they write the element type in a foreach. Writing var in a foreach is therefore a house convention of this guide. The Roslyn repository and the ReSharper default use var everywhere, and the shipped configuration suggests it everywhere; that wider preference is a house convention. Conventions that write the explicit type unless the type is visible on the right (the dotnet/runtime style limits var to a new expression or a cast, and the Aviva guidelines to an obvious type) rely on the type being readable in a code review without an IDE. For that reason an explicit type is accepted, and no build check reports it: IDE0007 is a suggestion.

Exceptions:

  • Declare the base type when the variable must be typed as the base: Payment payment = new CardPayment(9.99m, "XXXX-1111");.
  • Watch the literal. The literal decides the type: var price = 9.99; is a double, not a decimal, var ratio = 1.5; is a double, not a float, and var count = 0; is an int, not a long. Add the suffix (9.99m, 1.5f, 0L, see VAR-022) or write the explicit type when the default type is not the one the code needs.
  • A variable that holds an anonymous type must use var, because the type has no name; so must a foreach over a sequence of anonymous types.

See also: VAR-014 (field initializers), VAR-020 (keyword or BCL name), VAR-024 (decimal or double), VAR-541 (deconstruction), VAR-550 (out variables), VAR-551 (using declarations).

Scope: Local variables, loop variables, out variables and deconstruction targets; fields, properties and parameters cannot use var · Enforced: IDE0007 (suggestion), ReSharper: SuggestVarOrType_BuiltInTypes, SuggestVarOrType_SimpleTypes, SuggestVarOrType_Elsewhere · Config: csharp_style_var_for_built_in_types, csharp_style_var_when_type_is_apparent, csharp_style_var_elsewhere, resharper_csharp_for_built_in_types, resharper_csharp_for_simple_types, resharper_csharp_for_other_types, resharper_csharp_use_roslyn_logic_for_evident_types, resharper_suggest_var_or_type_built_in_types_highlighting, resharper_suggest_var_or_type_simple_types_highlighting, resharper_suggest_var_or_type_elsewhere_highlighting · Sources: MS-CONV, RT-STYLE, RS-VAR, MS-IDE, AV, MS-IDE-OPTIONS

VAR-011

Retired (2026-11-30) — superseded by VAR-010

VAR-012

Retired (2026-11-30) — superseded by VAR-010

VAR-013

Retired (2026-11-30) — superseded by VAR-010

VAR-014

DO write target-typed new() in a field or property initializer whose declared type is the type being created (private readonly StringBuilder _summary = new();); prefer var for locals (VAR-010) and collection expressions for collections (VAR-531).

✅ Correct

private readonly System.Text.StringBuilder _summary = new(); // declared type is the created type

public string AddNote(string note)
{
    _summary.AppendLine(note);

    return _summary.ToString();
}

❌ Incorrect — the type is written twice in the field declaration

private readonly System.Text.StringBuilder _summary = new System.Text.StringBuilder(); // type repeated

public string AddNote(string note)
{
    _summary.AppendLine(note);

    return _summary.ToString();
}

Why: A field cannot use var, so the declared type on the left is the only place the type appears. Target-typed new drops the second copy. Locals already avoid the repeat through var (VAR-010), and collections use collection expressions (VAR-531), so this rule covers the remaining case.

Exceptions:

  • When the declared type differs from the created type (an interface, a base class), write the created type: private readonly Payment _payment = new CardPayment(9.99m, "XXXX-1111");.

Scope: Field and property initializers whose declared type is the created type · Enforced: IDE0090, ReSharper: ArrangeObjectCreationWhenTypeEvident · Config: csharp_style_implicit_object_creation_when_type_is_apparent, resharper_csharp_object_creation_when_type_evident, resharper_csharp_object_creation_when_type_not_evident, resharper_arrange_object_creation_when_type_evident_highlighting · Sources: MS-CONV, RS-NEW, MS-IDE

VAR-015

DO write the default literal instead of default(T) wherever the compiler can infer the type (OrderStatus status = default;, return default;).

✅ Correct

public static OrderStatus GetInitialStatus() => default;

public static bool IsInitial(OrderStatus status = default) => status == default;

❌ Incorrect — the type is repeated in default(T)

public static OrderStatus GetInitialStatus() => default(OrderStatus); // redundant type

Why: The return type or the declaration already names the type, so default(OrderStatus) repeats it. The literal is shorter and stays correct when the declared type changes.

Exceptions:

  • Where no target type exists, such as an argument that must select an overload, write default(T).

Scope: default values where the target type is known · Enforced: IDE0034, ReSharper: ArrangeDefaultValueWhenTypeEvident · Config: csharp_prefer_simple_default_expression, resharper_csharp_default_value_when_type_evident, resharper_csharp_default_value_when_type_not_evident, resharper_arrange_default_value_when_type_evident_highlighting · Sources: MS-IDE, RS-SYNTAX

VAR-016

DO declare one variable per declaration statement and declare each local in the narrowest scope, directly before its first use.

✅ Correct

public static string Describe(Order order)
{
    int unitCount = 0; // declared directly before the loop that changes it
    foreach (OrderLine line in order.Lines)
    {
        unitCount += line.Quantity;
    }

    int lineCount = order.Lines.Count;
    decimal total = order.Total; // declared directly before its first use

    return $"{lineCount} lines, {unitCount} units, {total:N2} total";
}

❌ Incorrect — two declarators in one statement, and a local declared far from its first use

public static string Describe(Order order)
{
    int lineCount = order.Lines.Count, unitCount = 0; // two declarators in one statement
    decimal total = order.Total; // declared far from its first use
    foreach (OrderLine line in order.Lines)
    {
        unitCount += line.Quantity;
    }

    return $"{lineCount} lines, {unitCount} units, {total:N2} total";
}

Why: One declaration per statement gives each variable its own line to read, to comment and to change in a diff. A local declared next to its first use keeps the reader from scrolling back to find its type and initial value, and it limits the lines in which the variable can change. No tool checks this convention, so reviewers apply it.

Exceptions:

  • A for header may declare a counter and its bound together: for (int i = 0, count = items.Count; i < count; i++).

Scope: Local variable declarations · Enforced: Manual · Sources: MS-CONV, AV, GOOG

VAR-017

DO initialize a variable in its declaration with the value it needs and never assign it a value that is overwritten before it is read.

✅ Correct

public static string DescribeTotal(Order order)
{
    decimal total = order.Total; // initialized with the value it needs

    return $"Total {total:N2}";
}

❌ Incorrect — the first value is never read

public static string DescribeTotal(Order order)
{
    decimal total = 0m; // value is overwritten before it is read
    total = order.Total;

    return $"Total {total:N2}";
}

Why: A value that is replaced before anyone reads it is dead code. It also suggests that 0m matters, and it separates the declaration from the assignment that holds the real value. IDE0059 reports the unnecessary assignment in the build.

Exceptions:

  • An accumulator that starts at a literal and is changed before it is read is not covered, because the start value is read by the first change: int count = 0; followed by count++.
  • A local that every branch assigns may be declared without a value, because the compiler checks definite assignment.

Scope: Locals and fields that receive an initial value · Enforced: IDE0059, ReSharper: JoinDeclarationAndInitializer · Config: csharp_style_unused_value_assignment_preference, resharper_join_declaration_and_initializer_highlighting · Sources: MS-IDE, MS-CA, RS-INSPECT

Built-in types and literals

These rules cover which type holds a value and how its literal is written.

VAR-020

DO write the C# keyword (int, long, string, bool, object, nint, nuint) instead of the BCL type name (Int32, Int64, String, Boolean, Object, IntPtr, UIntPtr), including in member access such as string.Join and int.Parse.

✅ Correct

public static bool TryParseOrderId(string orderText, out int orderId)
{
    string trimmed = orderText.Trim();

    return int.TryParse(trimmed, CultureInfo.InvariantCulture, out orderId);
}

public static bool IsOpen(nint handle) => handle != 0;

❌ Incorrect — BCL names where a keyword exists

public static bool TryParseOrderId(string orderText, out int orderId)
{
    String trimmed = orderText.Trim(); // BCL name in a declaration

    return Int32.TryParse(trimmed, CultureInfo.InvariantCulture, out orderId); // BCL name in member access
}

public static bool IsOpen(IntPtr handle) => handle != 0; // IntPtr instead of nint

Why: int and Int32 name the same type, so using both in one code base gives the reader two spellings for one thing. The keyword form is the one the language specification and the Microsoft examples use. dotnet build does not report IDE0049 (IDE rule); the dotnet format style CI step does (TOOL-015), and so do Visual Studio and ReSharper (BuiltInTypeReferenceStyle). Since C# 11, nint and nuint are the same types as IntPtr and UIntPtr, so the keyword form costs nothing. BCL names stay for types that have no keyword: Guid, DateTimeOffset, TimeSpan.

Exceptions:

  • API names that contain a BCL name (Convert.ToInt32, BitConverter.ToInt64, reader.GetString) are method names, not type references; write them as declared.

Scope: Type references in declarations, casts, generic arguments and static member access · Enforced: ReSharper: BuiltInTypeReferenceStyle; not by dotnet build, but by the dotnet format style CI step (TOOL-015) · Config: dotnet_style_predefined_type_for_locals_parameters_members, dotnet_style_predefined_type_for_member_access, resharper_csharp_builtin_type_reference_style, resharper_csharp_builtin_type_reference_for_member_access_style, resharper_csharp_builtin_type_apply_to_native_integer, resharper_built_in_type_reference_style_highlighting, resharper_built_in_type_reference_style_for_member_access_highlighting · Sources: MS-CONV, RT-STYLE, RS-BUILTIN, SA

VAR-021

DO use int for integer values unless the value range, a native interop signature or a file or wire format needs long, short, byte or an unsigned type, and keep unsigned types out of public API signatures.

✅ Correct

public static int CountLines(Order order) => order.Lines.Count;

public static long GetTotalBytes(IEnumerable<FileInfo> files) => files.Sum(file => file.Length);

❌ Incorrect — narrow and unsigned types without a reason

public static short CountLines(Order order) => (short)order.Lines.Count; // narrow type without a reason

public uint Quantity { get; init; } // unsigned type in a public API

Why: Count, Length, indexers and most framework signatures use int, so int values flow through code without casts. A short saves two bytes per value and costs a cast at every use. Unsigned types other than byte are not part of the Common Language Specification, so some .NET languages cannot call a public member that exposes one. long is correct when the range requires it, as with file sizes. No tool checks this choice, so reviewers apply it.

Exceptions:

  • A native signature, a file format or a wire format dictates the width; match it (byte, ushort, uint) and keep the type inside the code that reads or writes the format.
  • Unsigned types are fine inside an implementation, such as uint hash arithmetic, as long as they do not appear in a public signature.

Scope: Integer fields, locals, parameters and return types · Enforced: Manual · Sources: MS-CONV, MS-FDG-ENUM

VAR-022

DO write the L, U and UL suffixes in upper case and the m, f and d suffixes in lower case (10_000L, 42U, 9.99m, 1.5f).

✅ Correct

const long MaxOrderValueCents = 10_000_000L;
const decimal UnitPrice = 9.99m;
const float ScaleFactor = 1.5f;
Console.WriteLine($"{MaxOrderValueCents} {UnitPrice} {ScaleFactor}");

❌ Incorrect — lower-case l and upper-case M and F

const long MaxOrderValueCents = 10_000_000l; // lower-case l looks like the digit 1
const decimal UnitPrice = 9.99M; // upper-case M suffix
const float ScaleFactor = 1.5F; // upper-case F suffix
Console.WriteLine($"{MaxOrderValueCents} {UnitPrice} {ScaleFactor}");

Why: A lower-case l is easy to read as the digit 1, so 10_000_000l looks like an eight-digit number ending in one. The compiler warns about it (CS0078). The compiler accepts 9.99M and 1.5F, and this rule does not: m, f and d stay lower case because the Microsoft examples write them that way and a single casing keeps searches and reviews uniform. Only l is checked by the build; reviewers check the rest.

Scope: Numeric literals with a type suffix · Enforced: CS0078 · Sources: MS-CONV, SA, MS-LANG-12

VAR-023

DO separate digit groups of a numeric literal with five or more digits with _ (1_000_000, 0xFF_FF), and write bit masks and flag values with 0b or 0x prefixes.

✅ Correct

const int MaxOrderValueCents = 1_000_000;
const int ExpressAndInsured = 0b_0011;
Console.WriteLine($"{MaxOrderValueCents} {ExpressAndInsured}");

❌ Incorrect — ungrouped digits and a bit mask in decimal

const int MaxOrderValueCents = 1000000; // digits not grouped
const int ExpressAndInsured = 3; // bit mask written in decimal
Console.WriteLine($"{MaxOrderValueCents} {ExpressAndInsured}");

Why: 1_000_000 reads as one million at a glance, while 1000000 needs a digit count. The separator does not change the value. A bit mask in 0b_0011 shows which bits are set, which 3 hides. No tool checks literal layout, so reviewers apply it.

Exceptions:

  • Numbers with four digits or fewer stay ungrouped (8080, 2026).
  • A value copied from a specification keeps the notation of that specification, such as a Unicode code point 0x1F600.

Scope: Numeric literals of five or more digits and bit-mask literals · Enforced: Manual · Sources: MS-CONV, AV

VAR-024

DO use decimal for monetary amounts and double for measured or scientific quantities, and compare double or float values against a tolerance instead of with == or !=.

✅ Correct

private const double WeightToleranceKilograms = 0.000_1;

public decimal UnitPrice { get; init; }

public static bool IsSameWeight(double weightInKilograms, double expectedKilograms) =>
    Math.Abs(weightInKilograms - expectedKilograms) < WeightToleranceKilograms;

❌ Incorrect — money in double and floating-point equality

public double UnitPrice { get; init; } // money in double

public static bool IsSameWeight(double weightInKilograms) => weightInKilograms == 1.1; // floating-point equality

Why: decimal stores base-10 digits, so 9.99m is exactly 9.99 and sums of prices carry no binary rounding error. double is a binary format: 0.1 + 0.2 == 0.3 is false. A measured weight already carries error, so a tolerance states the real question ("close enough") and == asks the wrong one. double is also the type that Math.Sqrt, Math.Sin and similar functions are defined on.

Exceptions:

  • Comparing with a value that was assigned unchanged, such as a sentinel 0.0, is exact.
  • Test for NaN with double.IsNaN, because NaN == NaN is false (CA2242).

Scope: Money, measurements and floating-point comparisons · Enforced: Manual · Sources: MS-CA, AV

VAR-025

DO NOT compare a Boolean expression with true or false, or select true or false with the conditional operator; use the expression itself or its negation.

✅ Correct

public static bool NeedsShipping(Order order) => !order.IsShipped && order.Lines.Count > 0;

❌ Incorrect — comparison with true and a conditional that returns true or false

public static bool IsDone(Order order) => order.IsShipped == true; // comparison with true

public static bool HasLines(Order order) => order.Lines.Count > 0 ? true : false; // conditional returning true or false

Why: order.IsShipped == true has the same value as order.IsShipped, and condition ? true : false has the same value as condition. The extra tokens make the reader check whether the author meant something else, such as a nullable bool or a side effect.

Exceptions:

  • A bool? is tested with flag == true or flag is true, because the comparison turns null into false.

Scope: Boolean expressions in conditions and assignments · Enforced: IDE0100, IDE0075 · Config: dotnet_style_prefer_simplified_boolean_expressions · Sources: MS-IDE, AV

VAR-026

DO use a char literal and the char overload of Contains, StartsWith, EndsWith, IndexOf, Split and StringBuilder.Append when the argument is a single character, and write the escape character as '\e'.

C# 13: The '\e' escape for the escape character (U+001B) needs C# 13. Before C# 13, write '\u001b'.

✅ Correct

public static bool IsCredit(string amountText) => amountText.StartsWith('-');

public static bool StartsWithEscape(string text) => text.StartsWith('\e');

❌ Incorrect — a one-character string where a char overload exists

public static bool IsCredit(string amountText) => amountText.StartsWith("-"); // one-character string

Why: The char overloads search for one value and skip the string handling; they compare ordinally, so they need no StringComparison (LANG-041). StartsWith(char) and EndsWith(char) have no StringComparison overload, so CA1307 has nothing to ask for; where a char call does have one (Contains(char, StringComparison)) and CA1307 reports it, pass StringComparison.Ordinal. The analyzers CA1847, CA1865, CA1866, CA1867 and CA1834 report the one-character string forms.

Exceptions:

  • A culture-sensitive comparison of a one-character text keeps the string and passes a StringComparison (LANG-041).

Scope: char values and string APIs that have char overloads · Enforced: CA1847, CA1865, CA1866, CA1867, CA1834 · Sources: MS-CA, MS-LANG-13

VAR-027

DO give every literal with a business meaning a named constant or configuration value (const int MaxLinesPerOrder = 50;), and keep inline only 0, 1, -1, "" and literals whose meaning the line states.

✅ Correct

private const decimal FreeShippingThreshold = 50m;

public static bool ShipsFree(Order order) => order.Total >= FreeShippingThreshold;

❌ Incorrect — a literal whose meaning only the author knows

public static bool ShipsFree(Order order) => order.Total >= 50m; // magic number

Why: 50m says nothing about why it is 50 or what unit it is in, and the same number in a second method looks unrelated. A name documents the meaning and gives one place to change it. No tool can tell what counts as a business meaning, so reviewers apply this rule. Where to declare the constant (const or static readonly) is on page 06 (VAR-510).

Exceptions:

  • A literal that a named local or parameter explains on the same line may stay: var paymentTimeout = TimeSpan.FromSeconds(30);.

Scope: Numeric and string literals with a business meaning · Enforced: Manual · Sources: AV, GOOG, MS-TEST

Strings

Text has three literal forms and one interpolation form. The first rule picks the literal form; the later rules cover the empty string, display text, interpolated raw strings and bytes.

VAR-030

DO write single-line text as a regular string literal and text that contains quotes, backslashes or several lines as a raw string literal ("""..."""), using $$""" when the text contains braces.

✅ Correct

const string Status = "Shipped";
const string OrderJson = """
    { "orderId": 7, "status": "Shipped" }
    """;
Console.WriteLine($"{Status}: {OrderJson}");

❌ Incorrect — escaped quotes and an embedded line break

const string OrderJson = "{ \"orderId\": 7, \"status\": \"Shipped\" }"; // escaped quotes
const string Body = "Line 1\nLine 2"; // embedded line break
Console.WriteLine($"{OrderJson} {Body}");

Why: A raw string literal needs no escape sequences, so JSON, paths and patterns read exactly as the program sees them. The closing delimiter sets the indentation that is removed, so the literal can follow the indentation of the code. A text with \" on every other word is hard to read and easy to break. With $$""", a single { is literal text and {{value}} is a hole (VAR-034). Only ReSharper reports this rule (UseRawString); dotnet build does not.

Exceptions:

  • A text that needs a control character or a character that cannot be typed (\t, \0, \u00A0) stays a regular literal with an escape, because a raw string cannot show it.

Scope: String literals · Enforced: ReSharper: UseRawString · Config: resharper_use_raw_string_highlighting · Sources: MS-CONV, AV, RS-INSPECT, MS-LANG-12

VAR-031

AVOID verbatim strings (@"...") for new file paths, regular expressions and other backslash-heavy text; write them as raw string literals.

✅ Correct

const string ExportPath = """C:\exports\orders.csv""";
const string SkuPattern = """^SKU-\d{1,6}$""";
Console.WriteLine($"{ExportPath} {SkuPattern}");

❌ Incorrect — verbatim strings for paths and patterns

const string ExportPath = @"C:\exports\orders.csv"; // verbatim string
const string SkuPattern = @"^SKU-\d{1,6}$"; // verbatim string
Console.WriteLine($"{ExportPath} {SkuPattern}");

Why: A verbatim string removes the backslash escapes but still needs "" for every quote, and it cannot span lines with the indentation of the code. A raw string literal removes both limits, so one literal form serves paths, patterns and JSON (VAR-030). The level is AVOID because verbatim strings still work and the compiler accepts them. No tool reports the choice, so reviewers apply it.

Exceptions:

  • Do not convert existing verbatim strings in code you are not otherwise changing.

Scope: Verbatim string literals (@"...") · Enforced: Manual · Sources: MS-CONV, AV

VAR-032

DO write an empty string as "", not as string.Empty, and test for missing text with string.IsNullOrEmpty (LANG-042).

✅ Correct

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

❌ Incorrect — string.Empty for the empty string

public string Notes { get; init; } = string.Empty; // string.Empty instead of ""

Why: Both forms produce the same interned string, so the choice is style only. "" is shorter, works where a constant is required (const string, attribute arguments, case ""), and is the form ReSharper prefers by default. To test whether text is missing, call string.IsNullOrEmpty rather than comparing with either form (LANG-042). StyleCop SA1122 asks for string.Empty, which no Microsoft source requires.

Scope: Empty string values · Enforced: Manual · Sources: RS-EMPTYSTR, SA, RT-GC

VAR-033

DO build display text with an interpolated string whose holes are expressions and whose format specifiers sit in the hole ($"Order {order.Id} total {order.Total:N2}"), instead of string.Format with numbered placeholders or ToString calls inside the holes.

✅ Correct

public static string Describe(Order order) => $"Order {order.Id}: {order.Lines.Count} lines, {order.Total:N2}";

❌ Incorrect — a ToString call in the hole, and numbered placeholders

public static string Describe(Order order) => $"Order {order.Id.ToString()}: {order.Lines.Count} lines"; // ToString call inside a hole

public static string GetLabel(Order order) =>
    string.Format(CultureInfo.InvariantCulture, "Order {0}: {1} lines", order.Id, order.Lines.Count); // numbered placeholders

Why: In an interpolated string the value sits where it appears in the output, and the compiler checks the expression. With {0} and {1} the reader matches numbers to arguments, and a changed argument list breaks the match silently. A ToString() in a hole repeats what the hole already does, and {order.Total:N2} states the format where it is used. An interpolated hole formats with the current culture, which is correct for user-facing display text; machine-readable values pass CultureInfo.InvariantCulture instead (LANG-043 states this exception).

Exceptions:

  • Never interpolate into a log message template; use constant templates with named placeholders (SEC-073).
  • A format string that is loaded at run time (a resource, a translation) cannot be an interpolated literal; use string.Format or CompositeFormat there.

See also: SEC-073 (log templates).

Scope: Composite and interpolated strings for display text (not log templates) · Enforced: IDE0071, ReSharper: UseStringInterpolation · Config: dotnet_style_prefer_simplified_interpolation, resharper_use_string_interpolation_highlighting · Sources: MS-CONV, AV, RS-INSPECT, MS-IDE

VAR-034

DO write an interpolated string that contains backslashes, quotes or line breaks as an interpolated raw string literal ($"""...""" or $$"""..."""), never as a verbatim interpolated string ($@"..." or @$"...").

✅ Correct

public static string BuildJson(int orderId)
{
    return $$"""
        { "orderId": {{orderId}}, "status": "Shipped" }
        """;
}

❌ Incorrect — a verbatim interpolated string with doubled quotes and braces

public static string BuildJson(int orderId) =>
    $@"{{ ""orderId"": {orderId}, ""status"": ""Shipped"" }}"; // verbatim interpolated string

Why: In a verbatim interpolated string every quote is written "" and every literal brace {{, so JSON turns into a row of doubled characters. With $$""", single braces and quotes are plain text and {{orderId}} is the hole. The text reads as the output will look.

Exceptions:

  • Single-line text without quotes, backslashes or braces uses a regular interpolated string (VAR-033).

Scope: Interpolated strings that contain backslashes, quotes or several lines · Enforced: Manual · Sources: MS-CONV, MS-LANG-12

VAR-035

DO write a constant byte sequence that represents ASCII or UTF-8 text as a UTF-8 string literal ("ORD"u8) instead of a byte array of character codes.

✅ Correct

public static ReadOnlySpan<byte> FileSignature => "ORD"u8;

❌ Incorrect — character codes in a byte array

public static ReadOnlySpan<byte> FileSignature => new byte[] { 0x4F, 0x52, 0x44 }; // character codes instead of a UTF-8 literal

Why: "ORD"u8 shows the text, and the compiler checks that it is valid UTF-8 and produces a ReadOnlySpan<byte>. The array { 0x4F, 0x52, 0x44 } makes the reader decode three numbers to find out that they spell ORD.

Exceptions:

  • Bytes that are not text, such as a binary file header with values above 0x7F, stay a byte array or span.

Scope: Constant byte sequences such as protocol markers and file signatures · Enforced: IDE0230, ReSharper: UseUtf8StringLiteral · Config: csharp_style_prefer_utf8_string_literals, resharper_use_utf8_string_literal_highlighting · Sources: MS-IDE, RS-INSPECT, MS-LANG-12

Date and time

Four types cover time: DateTimeOffset for a moment, DateOnly and TimeOnly for a calendar date and a time of day, and TimeSpan for a duration. A TimeProvider supplies the current time.

VAR-040

DO use DateTimeOffset for a point in time, such as when an order was placed or shipped.

✅ Correct

namespace Contoso.Orders;

public sealed record ShipmentEvent(int OrderId, DateTimeOffset ShippedAt);

❌ Incorrect — DateTime for a moment

namespace Contoso.Orders;

public sealed record ShipmentEvent(int OrderId, DateTime ShippedAt); // DateTime loses the offset

Why: A DateTimeOffset stores the instant together with its offset from UTC, so two values compare correctly wherever they were created. A DateTime carries only a Kind of Utc, Local or Unspecified, and an Unspecified value is read as local or UTC depending on the code that touches it. A DateTime loses the offset, so its meaning depends on Kind.

Exceptions:

  • A library or database column that exposes only DateTime is converted at the boundary: store UTC with Kind set to Utc and convert to DateTimeOffset where the value enters your code.

See also: NAM-026 (a DateTime that holds a UTC instant ends in Utc).

Scope: Points in time stored, compared, logged or sent between systems · Enforced: Manual · Sources: MS-DT, AV

VAR-041

DO read the current time from an injected TimeProvider (timeProvider.GetUtcNow()) or, where no provider is available, from DateTimeOffset.UtcNow, and never use DateTime.Now or DateTimeOffset.Now for values that are stored or compared.

✅ Correct

public static Order CreateOrder(int customerId, TimeProvider timeProvider) =>
    new(customerId, timeProvider.GetUtcNow());

❌ Incorrect — local time for stored values

public static Order CreateOrder(int customerId) =>
    new(customerId, DateTimeOffset.Now); // local time

public static string CreateStamp()
{
    DateTime createdAt = DateTime.Now; // local DateTime

    return createdAt.ToString("O", CultureInfo.InvariantCulture);
}

Why: Local time shifts twice a year in zones with daylight saving and differs between servers in different time zones, so two values stored from the same instant can disagree or sort wrongly. UTC has one value for one instant. TimeProvider also lets a test set the clock (VAR-044).

Exceptions:

  • Code that cannot take a provider, such as a static helper or the program entry point, reads DateTimeOffset.UtcNow.
  • A time that is only shown to a user in their own time zone may be converted to local time at the display step; the stored value stays UTC.

Scope: Reading the current time · Enforced: Manual · Sources: MS-DT, AV

VAR-042

DO use DateOnly for a calendar date such as a delivery date or birthday and TimeOnly for a time of day such as an opening time.

✅ Correct

namespace Contoso.Orders;

public sealed record DeliveryWindow(DateOnly DeliveryDate, TimeOnly EarliestTime, TimeOnly LatestTime);

❌ Incorrect — a date with a dummy time, and a time as text

namespace Contoso.Orders;

public sealed record DeliveryWindow(
    DateTime DeliveryDate, // date with a dummy time of day
    string EarliestTime); // time of day as text

Why: A delivery date has no time of day and no time zone. A DateTime for it carries a midnight that means nothing and can shift to the previous day in a time-zone conversion. A time of day kept as text ("08:30") has no type to validate it or compare it. DateOnly and TimeOnly state exactly what the value is.

Exceptions:

  • A time that belongs to a zone or an offset, such as a flight departure, is a DateTimeOffset (VAR-040).
  • A library that accepts only DateTime receives the converted value at the boundary.

Scope: Calendar dates and times of day without a time zone · Enforced: Manual · Sources: MS-DT

VAR-043

DO represent a duration as a TimeSpan (var paymentTimeout = TimeSpan.FromSeconds(30);) instead of an int or double number of milliseconds, seconds or minutes.

✅ Correct

public static Task WaitForPaymentAsync(TimeSpan timeout, CancellationToken cancellationToken = default) =>
    Task.Delay(timeout, cancellationToken);

❌ Incorrect — a duration as an int

public static Task WaitForPaymentAsync(int timeoutMilliseconds, CancellationToken cancellationToken = default) =>
    Task.Delay(timeoutMilliseconds, cancellationToken); // duration as an int

Why: A TimeSpan carries its unit, so TimeSpan.FromSeconds(30) cannot be read as 30 milliseconds. With an int, the caller must know whether the parameter takes seconds or milliseconds, and a wrong guess compiles. TimeSpan also supports arithmetic and comparison.

Exceptions:

  • When an int is unavoidable (a wire format, a configuration key, a legacy API), put the unit in the name (NAM-022).

See also: NAM-022 (unit at the end of a numeric name).

Scope: Durations, timeouts, intervals and delays · Enforced: Manual · Sources: MS-DT, AV

VAR-044

DO take a TimeProvider as a dependency in every class whose behaviour depends on the current time, and use FakeTimeProvider or a fake of your own in tests.

✅ Correct

namespace Contoso.Orders;

public sealed class InvoiceDueChecker(TimeProvider timeProvider)
{
    public bool IsOverdue(Invoice invoice) => timeProvider.GetUtcNow() > invoice.DueDate;
}

✅ Correct — a fixed clock for tests

namespace Contoso.Orders;

public sealed class FixedTimeProvider(DateTimeOffset utcNow) : TimeProvider
{
    public override DateTimeOffset GetUtcNow() => utcNow;
}

❌ Incorrect — the class reads the system clock

namespace Contoso.Orders;

public sealed class InvoiceDueChecker
{
    public static bool IsOverdue(Invoice invoice) => DateTimeOffset.UtcNow > invoice.DueDate; // untestable static clock
}

Why: A class that reads the system clock gives a different answer every time it runs, so a test of "overdue" would pass or fail depending on the day it runs. With a TimeProvider parameter, production code passes TimeProvider.System and a test passes a fixed clock. FakeTimeProvider comes from the Microsoft.Extensions.TimeProvider.Testing package and also moves the clock forward on demand.

Exceptions:

  • A class whose result does not depend on the current time needs no provider.
  • The composition root passes TimeProvider.System; it is the one place that names the system clock.

Scope: Classes whose behaviour depends on the current time · Enforced: Manual · Sources: AV, MS-TEST, MS-DT

Nullability

Nullable reference types make the compiler track which references can be null. These rules turn the feature on, say where ? belongs, and limit the null-forgiving operator.

VAR-050

DO enable nullable reference types in every project (<Nullable>enable</Nullable>) and fix every nullable warning (CS86xx) instead of suppressing it.

✅ Correct — the project setting

<PropertyGroup>
  <Nullable>enable</Nullable>
</PropertyGroup>

✅ Correct — a value that can be missing is declared nullable and handled

var customer = new Customer { Id = 7, Name = "Contoso Ltd" };
string? customerEmail = customer.Email;
int emailLength = customerEmail?.Length ?? 0; // null is handled where the value is read
Console.WriteLine(emailLength);

❌ Incorrect — null assigned to a non-nullable reference

string customerEmail = null; // null assigned to a non-nullable reference
Console.WriteLine(customerEmail);

Why: With nullable reference types enabled, the compiler warns at each place where a null could reach a dereference, which is where a NullReferenceException would be thrown at run time. A project without the setting gets none of these warnings. A suppressed warning leaves the defect in place and hides it from the next reader, so the fix is to change the type (string?), handle the null, or correct the caller. The shipped configuration reports CS8600, CS8602, CS8604 and CS8625 as warnings. The operators that handle null are on page 07 (LANG-022).

Exceptions:

  • Generated files (marked <auto-generated>) are compiled with nullable annotations off unless the generator writes #nullable enable; leave them as generated.
  • While migrating a large project, #nullable enable may be added file by file; the rule is met when the project property is on and no warning remains.

See also: VAR-051 (where ? belongs), VAR-053 (the null-forgiving operator), VAR-054 (nullable attributes). Setting the property for every project in Directory.Build.props is TOOL-014.

Scope: Every project; nullable reference type warnings in all code · Enforced: CS8600, CS8602, CS8604, CS8625 · Sources: MS-NRT, MS-CAOV, MS-MSBUILD

VAR-051

DO add ? to every reference-typed field, property, parameter, return type and type argument that can hold null, and to no other reference type.

✅ Correct

private readonly Dictionary<int, Order> _orders = [];

public void Add(Order order) => _orders[order.Id] = order;

public Order? FindOrder(int orderId) => _orders.GetValueOrDefault(orderId); // may return null

✅ Correct — properties, parameters and type arguments

public string? Note { get; set; }

public static IReadOnlyList<string?> CollectNotes(Customer customer, string? orderNote) =>
    [customer.Email, orderNote];

❌ Incorrect — the method can return null but its type says it cannot

private readonly Dictionary<int, Order> _orders = [];

public Order FindOrder(int orderId) => _orders.GetValueOrDefault(orderId); // may return null but is not marked ?

Why: The annotation is the contract: Order? tells every caller to check, and Order tells every caller it need not. A missing ? on a value that can be null moves the NullReferenceException from the method to its caller. A ? on a value that is never null makes callers add checks that cannot fail and hides the cases where null really occurs.

Exceptions:

  • A property whose getter never returns null but whose setter accepts it keeps the non-nullable type and adds [AllowNull].

See also: VAR-052 (nullable value types), VAR-525 (initialize collection properties).

Scope: Fields, properties, parameters, return types and type arguments of reference types · Enforced: CS8603, CS8618 · Sources: MS-NRT, MS-CONV

VAR-052

DO write a nullable value type with the ? suffix (int?, DateOnly?), never as Nullable<T>.

✅ Correct

namespace Contoso.Orders;

public sealed record OrderFilter(int? CustomerId, DateOnly? PlacedAfter);

❌ Incorrect — Nullable<T> spelled out

namespace Contoso.Orders;

public sealed record OrderFilter(Nullable<int> CustomerId, DateOnly? PlacedAfter); // Nullable<T> spelled out

Why: int? and Nullable<int> are the same type. The ? form is the one used by every other nullable annotation, including string?, so the chapter reads one way. Mixing both in a signature, as the incorrect example does, makes the reader check that they mean the same thing. No analyzer in the shipped configuration reports it, so reviewers apply the rule.

Exceptions:

  • Reflection code that names the open generic type uses typeof(Nullable<>), because the ? form does not exist for an open type.

Scope: Nullable value types · Enforced: Manual · Sources: SA, AV

VAR-053

AVOID the null-forgiving operator (!); use it only where a value is provably non-null but the compiler cannot see it, with a comment on the same line that says why.

✅ Correct — no !

public static int GetEmailLength(Customer customer) => customer.Email?.Length ?? 0;

✅ Correct — the compiler cannot see the guarantee, and the comment says why

public static string GetAssemblyName() =>
    typeof(Order).Assembly.GetName().Name!; // a loaded assembly always has a simple name

❌ Incorrect — ! hides a real null case

public static int GetEmailLength(Customer customer) => customer.Email!.Length; // ! hides a real null case

Why: The null-forgiving operator switches the warning off for one expression and has no effect at run time. If the value is null, the program still throws NullReferenceException, now with no warning to point at it. Customer.Email is string? because customers may have no e-mail address, so Email!.Length is a defect the operator hides. Use ! only where the guarantee exists but the compiler cannot see it, and write the guarantee in the comment. IDE0370 reports a ! that is provably unnecessary, but a reviewer judges whether a ! is justified.

See also: VAR-054 (annotate the method instead of using ! at each call).

Scope: The null-forgiving operator ! · Enforced: IDE0370 · Sources: MS-NRT, MS-IDE

VAR-054

DO annotate a Try-pattern or guard method with nullable analysis attributes such as [NotNullWhen(true)], [MaybeNullWhen(false)] or [NotNull] so callers need no !.

✅ Correct

using System.Diagnostics.CodeAnalysis;

namespace Contoso.Orders;

public sealed class OrderLookup(IReadOnlyDictionary<int, Order> orders)
{
    public bool TryFind(int orderId, [NotNullWhen(true)] out Order? order)
    {
        order = orders.GetValueOrDefault(orderId);

        return order is not null;
    }

    public decimal GetTotal(int orderId) => TryFind(orderId, out Order? order) ? order.Total : 0m;
}

❌ Incorrect — the caller dereferences a value the compiler still treats as possibly null

namespace Contoso.Orders;

public sealed class OrderLookup(IReadOnlyDictionary<int, Order> orders)
{
    public bool TryFind(int orderId, out Order? order)
    {
        order = orders.GetValueOrDefault(orderId);

        return order is not null;
    }

    public decimal GetTotal(int orderId) => TryFind(orderId, out Order? order) ? order.Total : 0m; // dereference without NotNullWhen
}

Why: The signature out Order? says the value may be null whatever the method returns, so the compiler warns at each caller. [NotNullWhen(true)] tells it that the value is not null when the method returns true, so the warning goes away at every call site, and the compiler checks the attribute against the method body. A ! at each caller repeats the claim and nothing checks it. Use [MaybeNullWhen(false)] on out T value for generic TryGet methods, [NotNull] on a parameter that a guard method proves non-null, and [NotNullIfNotNull] for a return value that is null only when an argument is null. Guard methods themselves are on page 10 (ERR-014).

Exceptions:

  • A method whose result and null state do not depend on each other needs no attribute.

See also: VAR-053 (the null-forgiving operator).

Scope: Try-pattern methods, guard methods and other methods whose null state depends on the result · Enforced: CS8602 · Sources: MS-NRT, MS-FDG-EXCTHROW

Sources

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

MS-CONV, MS-IDE, MS-IDE-OPTIONS, MS-CA, MS-CAOV, MS-MSBUILD, MS-LANG-12, MS-LANG-13, MS-NRT, MS-DT, MS-TEST, MS-FDG-ENUM, MS-FDG-EXCTHROW, RT-STYLE, RT-GC, SA, AV, GOOG, RS-VAR, RS-NEW, RS-SYNTAX, RS-BUILTIN, RS-EMPTYSTR, RS-INSPECT.

Previous: Naming: Fields, Parameters and Locals · Home · Next: Variables: Fields, Properties and Collections