Skip to content

Types and Members

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

Home · Rule index · Naming cheat sheet

This chapter covers how you declare types and their members: member order and modifiers, the choice between record, class and struct, parameter lists, optional parameters, events, operators, nested types and partial members. Names of types and members are set by page 03. How to declare fields and properties (const versus static readonly, initialisation) is set by page 06. Constructors, including the primary constructor, are covered by LANG-012. Exceptions and disposal are on page 10, and async members are on page 11.

The CA rules CA1003, CA1034 and CA2225 analyze only the public API by default, so their examples use public types. Rules marked Manual are checked in review and listed in the "Manual review only" table on page 15.

Rule index

ID Level Rule Enforced
TYPE-010 DO order the members of a type as fields, constructors, events, properties, indexers, operators, methods and nested types; within each group public before internal, protected and private, and static before instance. Manual
TYPE-011 DO write modifiers in the order public, private, protected, internal, file, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, required, volatile, async. IDE0036, ReSharper: ArrangeModifiersOrder
TYPE-012 DO write an access modifier on every type and member, including the default private and internal, except on interface members. IDE0040, ReSharper: ArrangeTypeMemberModifiers
TYPE-013 DO declare every class sealed unless it is designed and documented as a base class. CA1852, ReSharper: ClassCanBeSealed.Local
TYPE-014 DO NOT qualify a member with this. unless a parameter or local of the same name hides it. ReSharper: ArrangeThisQualifier
TYPE-020 DO choose a record for immutable data compared by value, a class for an object with identity or behaviour, and a struct only for a small (16 bytes or less), immutable value that is rarely boxed. Manual
TYPE-021 AVOID more than three parameters, not counting a trailing CancellationToken; group related values into a record parameter object instead. Manual
TYPE-022 CONSIDER splitting a method whose cyclomatic complexity exceeds 25 or that has more than 15 statements into smaller methods. CA1502
TYPE-023 DO use optional parameters with constant defaults instead of overloads that only supply default values, except in the public API of a shipped library, where you add overloads. Manual
TYPE-024 DO NOT return null from a method whose return type is a collection, Task or ValueTask; return an empty collection or Task.CompletedTask instead. CS8603
TYPE-025 DO make every field readonly that is assigned only in its declaration or constructor, and design types immutable (get-only or init properties) unless changing state is part of the type's purpose. IDE0044, ReSharper: FieldCanBeMadeReadOnly.Local
TYPE-026 DO declare a class that has only static members as static, and mark a method or property that uses no instance state static. CA1052, CA1822, ReSharper: ConvertToStaticClass
TYPE-030 DO declare events with EventHandler<TEventArgs> or EventHandler, never with a custom delegate type, and raise them as NAM-145 describes. CA1003
TYPE-031 DO provide a named method with the same behaviour for every overloaded operator of a public type (Add for +, Subtract for -), and overload == and != only together with Equals and GetHashCode. CA2225
TYPE-032 DO declare exactly one defining part and one implementing part for each partial member, keeping the implementing part in the generated or role-specific file of the type. Manual
TYPE-033 DO NOT declare a nested type public or protected; keep it private or move it to the top level when callers outside the containing type need it. CA1034

Member order and modifiers

These five rules set where a member sits in the file and how its declaration reads. Most of them are checked by the build; the order of members is checked in review.

TYPE-010

DO order the members of a type as fields, constructors, events, properties, indexers, operators, methods and nested types; within each group public before internal, protected and private, and static before instance.

✅ Correct

public const int MaxLength = 100; // Fields first: public, then private; static before instance
private static readonly TimeSpan MaxAge = TimeSpan.FromHours(1);
private readonly List<PendingOrder> _pending = [];

public event EventHandler<OrderShippedEventArgs>? Shipped;

public bool IsFull => _pending.Count >= MaxLength;

public void ShipNext() => Shipped?.Invoke(this, new OrderShippedEventArgs(_pending[0].OrderId));

public bool HasExpired(DateTimeOffset now) => _pending.Exists(pending => IsExpired(pending, now));

private static bool IsExpired(PendingOrder pending, DateTimeOffset now) => (now - pending.QueuedAt) > MaxAge;

private sealed record PendingOrder(int OrderId, DateTimeOffset QueuedAt); // Nested types last

❌ Incorrect — a private method above the public method, and a method above the field

namespace Contoso.Orders;

public sealed class OrderBacklog
{
    private bool HasIds() => _ids.Count > 0; // private method before the public method

    public bool IsEmpty() => !HasIds(); // method before the field

    private readonly List<int> _ids = [];
}

Why: A fixed order lets a reader find the state of a type at the top and its public surface next, without scanning. The order follows the StyleCop layout rules SA1201 to SA1204 and the dotnet/runtime habit of putting fields first. A primary constructor sits on the type line, so it takes the place of the constructor group between the fields and the events (a member snippet cannot show it). Aviva orders the remaining methods and private properties by calling order; StyleCop and the dotnet/runtime style agree on fields first.

Exceptions:

  • A member that implements an interface may sit next to the other members of its group; keep the group order.

Scope: Members of classes, records, structs and interfaces · Enforced: Manual · Sources: SA, RT-STYLE, AV, RS-LAYOUT

TYPE-011

DO write modifiers in the order public, private, protected, internal, file, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, required, volatile, async.

✅ Correct

private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(1); // access, static, readonly

public static async Task<int> CountAsync(IReadOnlyList<OrderLine> lines, CancellationToken cancellationToken = default)
{
    await Task.Delay(RetryDelay, cancellationToken);

    return lines.Count;
}

❌ Incorrect — static written before the access modifier

static private readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(1); // static before the access modifier

Why: One order means that static, readonly and async are always in the same column of a declaration, so a reader scans for them instead of parsing each line. IDE0036 compares every declaration with the list in csharp_preferred_modifier_order; Visual Studio and Rider offer a code fix that reorders the modifiers.

Exceptions:

  • partial and const are not in the option. Write partial directly before class, struct, interface or record (public sealed partial class), and write const after the access modifier (public const int MaxLines).

Scope: Modifier lists of types and members · Enforced: IDE0036, ReSharper: ArrangeModifiersOrder · Config: csharp_preferred_modifier_order, resharper_arrange_modifiers_order_highlighting · Sources: MS-IDE, RT-EC, RS-I-MODORDER

TYPE-012

DO write an access modifier on every type and member, including the default private and internal, except on interface members.

✅ Correct

namespace Contoso.Orders;

internal sealed class OrderCache // Access modifier on the type
{
    private readonly Dictionary<int, Order> _orders = [];

    public int Count => _orders.Count; // and on every member
}

❌ Incorrect — a property without an access modifier

namespace Contoso.Orders;

internal sealed class OrderCache
{
    private readonly Dictionary<int, Order> _orders = [];

    int Count => _orders.Count; // no access modifier
}

Why: A missing modifier forces the reader to remember the default, and the default differs by context: private for members, internal for top-level types. Writing it makes a review of the visible surface a read of the keywords. IDE0040 reports every declaration that omits the modifier.

Exceptions:

  • Interface members are public by definition and carry no modifier.

Scope: Types and members except interface members · Enforced: IDE0040, ReSharper: ArrangeTypeMemberModifiers · Config: dotnet_style_require_accessibility_modifiers, resharper_csharp_default_private_modifier, resharper_csharp_default_internal_modifier, resharper_arrange_type_member_modifiers_highlighting, resharper_arrange_type_modifiers_highlighting · Sources: MS-IDE, RT-STYLE, SA, RS-MODIFIERS

TYPE-013

DO declare every class sealed unless it is designed and documented as a base class.

✅ Correct

namespace Contoso.Orders;

internal sealed class OrderNumberGenerator // Sealed: nothing derives from it
{
    private int _last;

    public int Next() => Interlocked.Increment(ref _last);
}

❌ Incorrect — a class that nothing derives from is not sealed

namespace Contoso.Orders;

internal class OrderNumberGenerator // not sealed and never derived from
{
    private int _last;

    public int Next() => Interlocked.Increment(ref _last);
}

Why: An unsealed class promises that subclasses are safe, which obliges you to keep every virtual call order and protected member stable. A sealed class makes no such promise, and the JIT compiler can call its methods directly. CA1852 reports internal and private classes that nothing in the assembly derives from. It does not check public classes, so reviewers check those against this rule.

Exceptions:

  • A class designed and documented as a base class stays unsealed, for example an unsealed class whose events are raised from protected virtual methods (NAM-145).
  • Static classes cannot be sealed, and an abstract class exists to be derived from.

Scope: Classes not designed for inheritance · Enforced: CA1852, ReSharper: ClassCanBeSealed.Local · Config: resharper_class_can_be_sealed_local_highlighting, resharper_class_can_be_sealed_global_highlighting · Sources: RT-STYLE, AV, MS-CA, RS-INSPECT

TYPE-014

DO NOT qualify a member with this. unless a parameter or local of the same name hides it.

✅ Correct

private readonly List<OrderLine> _lines = [];

public void AddLine(OrderLine line) => _lines.Add(line); // No this.

❌ Incorrect — this. on a member that nothing hides (dotnet build does not report it; the dotnet format style CI step, Visual Studio and ReSharper do)

private readonly List<OrderLine> _lines = [];

public void AddLine(OrderLine line) => this._lines.Add(line); // unnecessary this.

Why: The _ prefix from the field naming rules already tells a reader that _lines is a member, so this. adds noise to every access. IDE0003 reports the qualifier. dotnet build does not report it; the dotnet format style CI step does (TOOL-015), as do Visual Studio at warning and ReSharper (ArrangeThisQualifier). StyleCop SA1101 requires this. on every member access; the shipped configuration turns that rule off.

Exceptions:

  • Qualify a member when a parameter or local of the same name hides it. Under the naming rules this is rare: fields carry a prefix and properties use PascalCase, so a hand-written parameter collides only with inherited members you do not own.

Scope: Instance and static member access · Enforced: ReSharper: ArrangeThisQualifier · Config: dotnet_style_qualification_for_field, dotnet_style_qualification_for_property, dotnet_style_qualification_for_method, dotnet_style_qualification_for_event, resharper_csharp_instance_members_qualify_members, resharper_csharp_static_members_qualify_members, resharper_arrange_this_qualifier_highlighting · Sources: RT-STYLE, ROSLYN, RS-QUAL, MS-IDE, AV

Type and member design

These rules choose the kind of type, the shape of a method and the mutability of state.

TYPE-020

DO choose a record for immutable data compared by value, a class for an object with identity or behaviour, and a struct only for a small (16 bytes or less), immutable value that is rarely boxed.

✅ Correct

namespace Contoso.Orders;

public sealed record ReturnLine(string Sku, int Quantity); // Data compared by value

public readonly record struct Money(decimal Amount); // 16 bytes, immutable value

public sealed class ReturnService(IOrderRepository repository) // Behaviour and dependencies
{
    public async Task<bool> ExistsAsync(int orderId, CancellationToken cancellationToken = default)
    {
        Order? order = await repository.FindAsync(orderId, cancellationToken);

        return order is not null;
    }
}

❌ Incorrect — a struct of more than 16 bytes with identity

namespace Contoso.Orders;

public struct CustomerProfile // more than 16 bytes
{
    public int Id { get; set; } // identity held by a mutable value type
    public string? Name { get; set; }
    public string? Email { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public decimal CreditLimit { get; set; }
    public OrderStatus LastStatus { get; set; }
}

❌ Incorrect — a record that holds behaviour and changes state

namespace Contoso.Orders;

public sealed record OrderLifecycle(int OrderId) // record used for behaviour
{
    public OrderStatus Status { get; private set; }

    public void MarkPaid() => Status = OrderStatus.Paid;
}

Why: A positional record gives you value equality, ToString and with copies, which fit data and are wrong for an object whose identity matters. A class is compared by reference, which fits an entity or a service. A struct is copied on every assignment and boxed when stored as object or an interface, so it pays off only for a value of 16 bytes or less that is immutable and rarely boxed (the Framework Design Guidelines criterion). The query method ExistsAsync in the example is named by DATA-012.

Exceptions:

  • A mutable struct is acceptable only as a struct enumerator or a ref struct cursor on a hot path (VAR-543).

Scope: Choosing between record, class and struct · Enforced: Manual · Sources: MS-FDG-CLASSSTRUCT, AV, GOOG

TYPE-021

AVOID more than three parameters, not counting a trailing CancellationToken; group related values into a record parameter object instead.

✅ Correct

namespace Contoso.Orders;

public sealed record PlaceOrderRequest(
    int CustomerId,
    IReadOnlyList<OrderLine> Lines,
    ShippingOptions Options,
    string? CouponCode);

public sealed class OrderPlacement(TimeProvider timeProvider)
{
    public Task<Order> PlaceOrderAsync(PlaceOrderRequest request, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(request);

        return Task.FromResult(new Order(request.CustomerId, timeProvider.GetUtcNow()));
    }
}

❌ Incorrect — four parameters before the token

public static Task<Order> PlaceOrderAsync(
    int customerId,
    IReadOnlyList<OrderLine> lines,
    ShippingOptions options,
    string? couponCode, // fourth parameter before the token
    CancellationToken cancellationToken = default)
{
    return Task.FromResult(new Order(customerId, TimeProvider.System.GetUtcNow()));
}

Why: A call with four or more positional arguments is hard to read, and callers can swap two arguments of the same type without a compile error. A record names each value at the call site, and adding a fifth value later changes one type instead of every caller. The token stays out of the count because it is a cross-cutting parameter that the async rules on page 11 place last.

Exceptions:

  • A method that implements an interface or overrides a member you do not control keeps that signature.

Scope: Parameter lists of methods and constructors · Enforced: Manual · Sources: AV, GOOG, MS-FDG-PARAMDESIGN

TYPE-022

CONSIDER splitting a method whose cyclomatic complexity exceeds 25 or that has more than 15 statements into smaller methods.

✅ Correct

public static decimal PriceOrder(IReadOnlyList<OrderLine> lines)
{
    ValidateLines(lines);

    return CalculateTotal(lines); // A short method that coordinates helpers
}

private static void ValidateLines(IReadOnlyList<OrderLine> lines)
{
    ArgumentNullException.ThrowIfNull(lines);
    ArgumentOutOfRangeException.ThrowIfZero(lines.Count);
}

private static decimal CalculateTotal(IReadOnlyList<OrderLine> lines) => lines.Sum(line => line.Amount);

❌ Incorrect — outline of one method that validates, prices, discounts and taxes (about 40 statements and more than 25 branches; the body is elided)

public static decimal PriceOrder(IReadOnlyList<OrderLine> lines) // one method does validation, pricing and discounts
{
    decimal total = 0m;
    foreach (OrderLine line in lines)
    {
        // ... 12 statements: stock checks and line pricing
    }

    // ... 28 statements: coupon rules, tax tables and shipping surcharges
    return total;
}

Why: Each branch doubles the cases a test must cover, and a method past 25 branches is hard to cover and hard to read in one screen. Named helpers turn the outline of the method into its documentation. CA1502 measures the complexity and ships at suggestion, so Visual Studio and Rider show it as a hint and the build does not fail; the 15-statement limit has no tool and is checked in review.

Exceptions:

  • A flat switch that maps values to results can pass 25 branches and stay readable. Keep it when every arm is one expression.

Scope: Method size and complexity · Enforced: CA1502 · Sources: MS-CA, AV

TYPE-023

DO use optional parameters with constant defaults instead of overloads that only supply default values, except in the public API of a shipped library, where you add overloads.

✅ Correct

public static string FormatOrderNumber(int orderId, int width = 6)
{
    return orderId.ToString(System.Globalization.CultureInfo.InvariantCulture).PadLeft(width, '0');
}

❌ Incorrect — an overload that only fills a default

public static string FormatOrderNumber(int orderId) => FormatOrderNumber(orderId, 6); // only fills a default

public static string FormatOrderNumber(int orderId, int width)
{
    return orderId.ToString(System.Globalization.CultureInfo.InvariantCulture).PadLeft(width, '0');
}

Why: One method with a default is one signature to document, test and keep consistent, where two overloads can drift apart. The compiler copies a default into the caller's code, so changing it in a shipped library does not change callers that are already compiled; that is the reason library authors keep overloads. The Framework Design Guidelines advise overloads instead of default arguments in a framework's public API, where they protect binary compatibility of shipped libraries.

Exceptions:

  • In the public API of a library you ship to other teams, add an overload instead of a default value.
  • A default must be a compile-time constant. Use null and assign the real default in the body when it is not.

Scope: Optional parameters and overloads · Enforced: Manual · Sources: MS-FDG-OVERLOAD, MS-CONV, AV

TYPE-024

DO NOT return null from a method whose return type is a collection, Task or ValueTask; return an empty collection or Task.CompletedTask instead.

✅ Correct

public static IReadOnlyList<OrderLine> GetLinesOrEmpty(Order? order) => order?.Lines ?? []; // Never null

public static Task NotifyAsync(bool isEnabled, Func<Task> send) => isEnabled ? send() : Task.CompletedTask;

❌ Incorrect — null instead of a completed task

public static Task NotifyAsync(bool isEnabled, Func<Task> send)
{
    if (!isEnabled)
    {
        return null; // null instead of a completed task
    }

    return send();
}

Why: A caller loops over a collection or awaits a Task without a null check. A null collection throws NullReferenceException in the first foreach, and await on a null Task throws it at the call site, away from the cause. The compiler reports the return as CS8603 because the return type is not nullable. How to expose collections from public members is set by VAR-535.

Exceptions:

  • A method that returns a single object may return null when its return type is annotated T?; the annotation tells the caller to check.

Scope: Methods returning collections, Task or ValueTask · Enforced: CS8603 · Sources: MS-FDG-COLL, MS-ASYNCRET, AV

TYPE-025

DO make every field readonly that is assigned only in its declaration or constructor, and design types immutable (get-only or init properties) unless changing state is part of the type's purpose.

✅ Correct

namespace Contoso.Orders;

public sealed class PriceList
{
    private readonly Dictionary<string, decimal> _prices = new(StringComparer.Ordinal); // readonly: assigned once

    public void Set(string sku, decimal price) => _prices[sku] = price;

    public decimal Find(string sku) => _prices.GetValueOrDefault(sku);
}

public sealed class Receipt
{
    public required int OrderId { get; init; } // init: set once, then read-only
}

❌ Incorrect — a field that is never reassigned but is not readonly

namespace Contoso.Orders;

public sealed class PriceList
{
    private Dictionary<string, decimal> _prices = new(StringComparer.Ordinal); // never reassigned but not readonly

    public void Set(string sku, decimal price) => _prices[sku] = price;

    public decimal Find(string sku) => _prices.GetValueOrDefault(sku);
}

Why: readonly lets the compiler and the reader rule out reassignment, and an immutable type needs no locking when two threads read it. A readonly field still lets you change the contents of a collection it holds, as Set does, so the keyword guards the reference and not the data. How to declare properties is set by VAR-520.

Exceptions:

  • A type whose job is to change state, such as Order.Status, uses a private set and exposes methods that make the change.
  • A mutable struct field that the code mutates in place cannot be readonly.

Scope: Fields and the mutability of types · Enforced: IDE0044, ReSharper: FieldCanBeMadeReadOnly.Local · Config: dotnet_style_readonly_field, resharper_field_can_be_made_read_only_local_highlighting · Sources: MS-FDG-CLASSSTRUCT, MS-IDE, GOOG, RS-INSPECT

TYPE-026

DO declare a class that has only static members as static, and mark a method or property that uses no instance state static.

✅ Correct

namespace Contoso.Orders;

public static class OrderMath // Only static members: the class is static
{
    public static decimal CalculatePercent(decimal part, decimal whole) => whole == 0m ? 0m : part / whole;
}

❌ Incorrect — a class with only static members that is not static, and a method that uses no instance state

namespace Contoso.Orders;

public class OrderMath // only static members but not static
{
    public static decimal CalculatePercent(decimal part, decimal whole) => whole == 0m ? 0m : part / whole;
}

public sealed class OrderFormatter
{
    public string GetPrefix() => "ORD"; // uses no instance state
}

Why: A static class cannot be instantiated or derived from, so the compiler enforces what the type is. A static member tells the reader that a call depends on its arguments only. CA1052 reports the first case on the class line, and CA1822 reports the second on the member.

Exceptions:

  • A member that implements an interface member or overrides a base member cannot be static.

Scope: Classes with only static members, and members that use no instance state · Enforced: CA1052, CA1822, ReSharper: ConvertToStaticClass · Config: resharper_convert_to_static_class_highlighting · Sources: MS-CA, AV, RS-INSPECT

Events, operators, nested and partial types

These rules cover how events, operators, nested types and partial members are declared.

TYPE-030

DO declare events with EventHandler<TEventArgs> or EventHandler, never with a custom delegate type, and raise them as NAM-145 describes.

✅ Correct

namespace Contoso.Orders;

public sealed class Shipment
{
    public event EventHandler<OrderShippedEventArgs>? Shipped; // EventHandler<TEventArgs>

    public void Complete(int orderId) => Shipped?.Invoke(this, new OrderShippedEventArgs(orderId));
}

❌ Incorrect — an event with a custom delegate type

namespace Contoso.Orders;

public delegate void ShippedCallback(int orderId);

public sealed class Shipment
{
    public event ShippedCallback? Shipped; // custom delegate type for an event

    public void Complete(int orderId) => Shipped?.Invoke(orderId);
}

Why: Every .NET event handler has the (object? sender, TEventArgs e) shape, so subscribers and tools expect it. A custom delegate type breaks that shape and cannot grow a parameter without breaking subscribers, while a subclass of EventArgs can. How an event is raised is owned by NAM-145: a sealed class, as above, raises it directly, and an unsealed class raises it from a protected virtual On<EventName> method. CA1003 reports the custom delegate on the event line.

Exceptions:

  • EventHandler without type arguments suits an event that carries no data.

Scope: Event declarations and raising · Enforced: CA1003 · Sources: MS-FDG-EVENT, MS-CA, AV

TYPE-031

DO provide a named method with the same behaviour for every overloaded operator of a public type (Add for +, Subtract for -), and overload == and != only together with Equals and GetHashCode.

✅ Correct

namespace Contoso.Orders;

public readonly record struct Money(decimal Amount)
{
    public static Money operator +(Money left, Money right) => Add(left, right);

    public static Money Add(Money left, Money right) => new(left.Amount + right.Amount); // Named alternate for +
}

❌ Incorrect — an operator without a named alternate

namespace Contoso.Orders;

public readonly record struct Money(decimal Amount)
{
    public static Money operator +(Money left, Money right) => new(left.Amount + right.Amount); // no named alternate
}

Why: Not every .NET language can call a C# operator, and a named method such as Add shows up in IntelliSense and in method groups. Forwarding the operator to the method keeps one implementation. CA2225 reports the operator that has no named alternate.

Exceptions:

  • A record or record struct generates ==, !=, Equals and GetHashCode together, so you do not write them.

Scope: Overloaded operators of public types · Enforced: CA2225 · Sources: MS-FDG-PARAMS, MS-CA

TYPE-032

DO declare exactly one defining part and one implementing part for each partial member, keeping the implementing part in the generated or role-specific file of the type.

C# 13: Partial properties and indexers need C# 13. Partial constructors and events need C# 14. Before C# 13 only partial methods can have a separate implementing part.

✅ Correct

namespace Contoso.Orders;

public sealed partial class OrderSnapshot // OrderSnapshot.cs: the defining part
{
    public partial string Label { get; }
}

public sealed partial class OrderSnapshot // OrderSnapshot.Label.cs: the implementing part
{
    private readonly List<OrderLine> _lines = [];

    public partial string Label => $"Snapshot of {_lines.Count} lines";
}

❌ Incorrect — the implementing part sits in an unrelated file

namespace Contoso.Orders;

public sealed partial class OrderSnapshot
{
    public partial string Label { get; }
}

public sealed partial class OrderSnapshot // OrderHelpers.cs: a file that holds unrelated helpers
{
    private readonly List<OrderLine> _lines = [];

    public partial string Label => $"Snapshot of {_lines.Count} lines"; // implementation separated from its role file
}

Why: A partial member is one member in two places. If the implementing part lives in a file named for something else, a reader who opens the defining part cannot predict where to find the body. Name the file after its role (OrderSnapshot.Label.cs, or OrderSnapshot.g.cs for generated code). The compiler already rejects parts that do not match, but no tool checks where the parts live.

Exceptions:

  • A source generator that writes the implementing part chooses the file name; accept it and keep the defining part in the file you own.

Scope: Partial constructors, events, properties and methods with implementations · Enforced: Manual · Sources: MS-LANG-13, MS-LANG-14

TYPE-033

DO NOT declare a nested type public or protected; keep it private or move it to the top level when callers outside the containing type need it.

✅ Correct

namespace Contoso.Orders;

public sealed class OrderImporter
{
    public static OrderLine Import(string sku, int quantity)
    {
        var row = new CsvRow(sku, quantity);

        return new OrderLine(row.Sku, row.Quantity, 0m);
    }

    private sealed record CsvRow(string Sku, int Quantity); // private nested type
}

❌ Incorrect — a public nested type

namespace Contoso.Orders;

public sealed class OrderImporter
{
    public static CsvRow Read(string sku, int quantity) => new(sku, quantity);

    public sealed record CsvRow(string Sku, int Quantity); // public nested type
}

Why: A caller who needs the type writes OrderImporter.CsvRow, which ties the type to its container and keeps it out of its own file. A private nested type is an implementation detail, and a top-level type lives in its own file (NAM-118 names both the same way). Public nested types used as namespaces in disguise couple callers to the container. CA1034 ships as a hint because it also reports C# 14 extension blocks as nested public types.

Exceptions:

  • An internal nested type is allowed for helpers that other types of the assembly share.

Scope: Nested types · Enforced: CA1034 · Sources: MS-CA, MS-FDG-TYPES

  • NAM-145: the On<EventName> method that raises an event.
  • NAM-118: names of nested types.
  • VAR-520 and VAR-535: how to declare properties and how to expose collections.
  • VAR-526: when a member is a method and not a property.
  • DATA-012: names of query methods such as ExistsAsync.
  • LANG-012: primary constructors.
  • ERR-014 and ERR-020: argument validation and disposal of the types declared here.
  • Page 11: the CancellationToken parameter that TYPE-021 leaves out of the count.

Sources

AV · GOOG · MS-ASYNCRET · MS-CA · MS-CONV · MS-FDG-CLASSSTRUCT · MS-FDG-COLL · MS-FDG-EVENT · MS-FDG-OVERLOAD · MS-FDG-PARAMDESIGN · MS-FDG-PARAMS · MS-FDG-TYPES · MS-IDE · MS-LANG-13 · MS-LANG-14 · ROSLYN · RS-I-MODORDER · RS-INSPECT · RS-LAYOUT · RS-MODIFIERS · RS-QUAL · RT-EC · RT-STYLE · SA


Previous: Language Features · Home · Next: Comments and Documentation