Skip to content

Naming Cheat Sheet and Principles

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

Home · Rule index · Naming cheat sheet

This chapter opens with the naming cheat sheet, one table that gives the style of every identifier kind: PascalCase, camelCase, or camelCase with the _ prefix for non-public fields. The rules after it apply to every identifier, whatever its kind: how to write acronyms and abbreviations, how to give a name its meaning, and how to name solutions, projects, namespaces and files. Names of types, enums, delegates, methods, properties and events are on page 03, names of fields, constants, parameters and locals on page 04, and test names on page 12; how to declare a field or property (const vs static readonly, readonly, initialisation) is on page 06.

Most rules in this chapter are Manual: no analyzer checks word choice, so reviewers check them (TOOL-018). The Enforced line of each rule says which ones a diagnostic checks.

Naming cheat sheet

One row per identifier kind, ordered types, members, fields, then parameters and locals. Find the kind of name you are writing, copy the convention, and follow the Rule link for exceptions and enforcement. Solutions, projects, namespaces, files and test projects are not rows in this table: they are named by NAM-030 to NAM-036 in this chapter, and test names by TEST-010 to TEST-014.

Identifier kind Convention Example Rule
class (also static class) PascalCase noun public sealed class InvoiceNumberGenerator; NAM-110
abstract class PascalCase noun, no Base suffix public abstract class PaymentProvider; NAM-111
record PascalCase noun public sealed record OrderPlaced(int OrderId); NAM-112
record struct PascalCase noun public readonly record struct Money(decimal Amount, string Currency); NAM-113
struct PascalCase noun public readonly struct Quantity; NAM-114
interface I + PascalCase public interface IPaymentGateway; NAM-115
generic type PascalCase noun, no arity public sealed class Result<TValue>; NAM-116
enum singular PascalCase noun public enum FulfillmentState { Pending, Shipped } NAM-120
flags enum plural PascalCase noun, None = 0 [Flags] public enum NotificationChannels { None = 0, Email = 1, Sms = 2 } NAM-121
enum member PascalCase, no enum-name prefix public enum PaymentState { Authorized, Captured } NAM-122
delegate PascalCase + Callback; events use EventHandler<TEventArgs>, not a custom delegate public delegate void OrderShippedCallback(int orderId); NAM-123
event-args class PascalCase + EventArgs public sealed class PaymentCapturedEventArgs : EventArgs; NAM-124
attribute class PascalCase + Attribute [AttributeUsage(AttributeTargets.Class)] public sealed class AuditedAttribute : Attribute; NAM-125
exception class PascalCase + Exception public sealed class PaymentDeclinedException : Exception { public PaymentDeclinedException() { } public PaymentDeclinedException(string message) : base(message) { } public PaymentDeclinedException(string message, Exception innerException) : base(message, innerException) { } } NAM-126
extension class static, <ExtendedType>Extensions public static class TimeProviderExtensions; NAM-127
extension block receiver camelCase noun public static class OrderExtensions { extension(Order order) { public bool IsLarge => order.Total > 1_000m; } } NAM-137
nested type PascalCase noun private sealed class CacheEntry; NAM-118
file-local type PascalCase noun file sealed class OrderCsvRow; NAM-119
type parameter T or T + PascalCase public interface IHandler<TCommand>; NAM-117
type with a role suffix noun that names the role; no Impl, Helper, Manager, Utils, Util, Utility, Utilities, Info, Data, Wrapper, Processor public sealed class OrderPriceCalculator; NAM-128
type that could clash specific noun, not a BCL type or namespace name public sealed class FulfillmentJob; NAM-129
method PascalCase verb phrase public string FormatOrderNumber(int orderId) => $"ORD-{orderId:D6}"; NAM-130
async method PascalCase verb phrase + Async public async Task SaveOrderAsync(CancellationToken cancellationToken = default) => await Task.Delay(TimeSpan.FromMilliseconds(10), cancellationToken); NAM-131
Boolean method Is/Has/Can + PascalCase public static bool HasLines(Order order) => order.Lines.Count > 0; NAM-132
Try method Try + verb, bool result, out parameter last public static bool TryParseQuantity(string text, out int quantity) => int.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out quantity); NAM-133
local function PascalCase verb phrase static decimal RoundToCents(decimal amount) => decimal.Round(amount, 2, MidpointRounding.AwayFromZero); NAM-134
property PascalCase noun public decimal Total { get; init; } NAM-140
Boolean property Is/Has/Can + PascalCase public bool IsShipped { get; private set; } NAM-141
collection property plural PascalCase noun public IReadOnlyList<string> Tags { get; init; } = []; NAM-142
indexer this[...], default name Item public OrderLine this[int lineNumber] => new($"SKU-{lineNumber}", 1, 0m); NAM-143
event PascalCase verb (Shipped, Closing) public event EventHandler<OrderShippedEventArgs>? Shipped; NAM-144
event-raising method protected virtual On + event name public class Shipment { public event EventHandler<OrderShippedEventArgs>? Shipped; protected virtual void OnShipped(OrderShippedEventArgs e) => Shipped?.Invoke(this, e); } NAM-145
event handler On + source + event private void OnOrderShipped(object? sender, OrderShippedEventArgs e) => Console.WriteLine(e.OrderId); NAM-146
explicit interface implementation interface member name and parameter names unchanged public readonly record struct OrderNumber(int Value) : IFormattable { string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => Value.ToString(format, formatProvider); } NAM-135
partial member same PascalCase name and parameter names in every part partial void OnStatusChanged(OrderStatus status); NAM-136
private instance field _camelCase private readonly List<OrderLine> _lines = []; NAM-200
private static field camelCase (no s) private static int _instanceCount; NAM-210
thread-static field camelCase, like any private static field (no t) [ThreadStatic] private static int _depth; NAM-212
private readonly instance field _camelCase private readonly List<OrderLine> _lines = []; NAM-201
private static readonly field PascalCase (no prefix) private static readonly HttpClient SharedClient = new(); NAM-211
public static readonly field PascalCase public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30); NAM-213
public field (interop struct only) PascalCase public int X; NAM-203
protected or protected internal instance field _camelCase or PascalCase, both accepted protected int _retryCount; NAM-203
internal instance field _camelCase internal int _retryCount; NAM-202
public or internal constant PascalCase internal const int MaxLinesPerOrder = 50; NAM-214
private constant PascalCase private const int MaxRetries = 3; NAM-215
local constant camelCase preferred, PascalCase accepted const int maxAttempts = 3; NAM-216
explicit backing field _camelCase of the property name private string _displayName = ""; NAM-204
any field, parameter or local meaning, not type (no m_, str, i) private readonly string _customerName = ""; NAM-205
constant field PascalCase, never SCREAMING_CASE public const int HttpsPort = 443; NAM-206
parameter camelCase noun public static decimal ApplyDiscount(decimal orderTotal, decimal discountRate) => orderTotal * (1 - discountRate); NAM-220
primary-constructor parameter camelCase (class/struct), PascalCase (positional record) public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice); NAM-221
constructor parameter stored in a field camelCase parameter, stored in an _camelCase field public Shipment(string trackingNumber) / _trackingNumber = trackingNumber; NAM-222
extension this parameter camelCase noun of the extended type public static class InvoiceExtensions { public static bool IsOverdue(this Invoice invoice, DateTimeOffset now) => now > invoice.DueDate; } NAM-223
out/ref/in parameter camelCase, no out/ref prefix public static void Swap(ref int first, ref int second) => (first, second) = (second, first); NAM-224
params parameter plural camelCase noun public static int CountSkus(params string[] skus) => skus.Length; NAM-225
optional parameter camelCase public static string PadOrderNumber(string orderNumber, int totalWidth = 10) => orderNumber.PadLeft(totalWidth); NAM-226
local variable camelCase noun public static int ParseQuantity(string text) => int.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out int quantity) ? quantity : 0; NAM-230
loop variable i, j, k for counters; element noun in foreach for (int i = 0; i < lines.Count; i++) / foreach (OrderLine line in order.Lines) NAM-231
lambda parameter camelCase; single letter only in one-liners public static bool HasEven(IReadOnlyList<int> numbers) => numbers.Any(number => number % 2 == 0); NAM-232
discard _ public static bool IsQuantity(string text) => int.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out _); NAM-233
tuple element PascalCase in signatures public static (int Count, decimal Total) Summarize(IReadOnlyList<OrderLine> lines) => (lines.Count, lines.Sum(line => line.Amount)); NAM-234
deconstruction variable camelCase (int count, decimal total) = (3, 9.99m); NAM-235
pattern variable camelCase public static bool IsLargeCard(Payment payment) => payment is CardPayment card && card.Amount > 1_000m; NAM-236
LINQ range variable camelCase element noun IEnumerable<int> evens = Enumerable.Range(1, 10).Where(number => number % 2 == 0); NAM-237
using variable camelCase using var buffer = new MemoryStream(); NAM-238
catch variable ex catch (FormatException ex) NAM-239
anonymous-type member PascalCase public static IEnumerable<decimal> SelectTotals(IEnumerable<Order> orders) => orders.Select(order => new { order.Id, OrderTotal = order.Total }).Select(summary => summary.OrderTotal); NAM-240
named argument exact camelCase parameter name public static string PadOrderId(int orderId) => orderId.ToString(System.Globalization.CultureInfo.InvariantCulture).PadLeft(totalWidth: 6, paddingChar: '0'); NAM-227
label PascalCase RetryPayment: NAM-241

Rule index

ID Level Rule Enforced
NAM-010 DO write a two-letter acronym in PascalCase identifiers fully in upper case (IOStream, UIState) and an acronym of three or more letters with only its first letter capitalized (XmlReader, HttpClientFactory, JsonOptions). Manual
NAM-011 DO write an acronym that starts a camelCase identifier entirely in lower case, whatever its length (ioStream, xmlReader, httpClient, _uiState). Manual
NAM-012 DO write Id and Ok as ordinary words (CustomerId, IsOk), closed compounds as one word (Email, Endpoint, Metadata, Callback) and the two-word terms UserName, FileName and LogOn with a capital on each word, never ID, OK, EMail, Username or Filename. Manual
NAM-013 DO NOT shorten a word in an identifier except to the approved forms Id, Ok, Db, IO, UI, Xml, Json, Http, Url, Uri, the loop counters i, j, k, the catch variable ex, the event-data parameter e (NAM-145) and a one-letter parameter of a single-line lambda (NAM-232). Manual
NAM-014 DO write identifiers as English words spelled with the ASCII letters A-Z, a-z and digits only. Manual
NAM-015 DO NOT declare an identifier that needs the @ verbatim prefix, such as @class or @event, except in generated interop code that must mirror an external name. Manual
NAM-016 DO NOT write an underscore inside an identifier; the only underscores allowed are the single leading _ of a non-public instance field (a protected one included) or mutable static field, followed by camelCase (_orderCount, never _order_count, s_orderCount, t_depth or orderCount_s), the discard _ and the separators of test method names (TEST-011). CA1707, IDE1006
NAM-017 DO NOT give two identifiers in the same scope names that differ only by letter case. CA1708
NAM-020 DO name a Boolean variable, field or parameter as an affirmative statement that starts with is, has, can or should (isPaid, hasLines, canShip, _isClosed). Manual
NAM-021 DO name a variable, field or parameter that holds a collection with a plural noun (orders, lines, _pendingOrders), not with a List, Array or Collection suffix. Manual
NAM-022 DO put the unit at the end of the name of a numeric field, parameter, property or local that is not a TimeSpan (weightInKilograms, MaxPayloadBytes, distanceInKilometres). Manual
NAM-023 DO NOT tell two names apart with a numeric suffix (order2, customer1, ProcessOrder2); name each after its role instead (originalOrder, updatedOrder). Manual
NAM-024 DO name the default implementation of an interface after the interface without its I prefix (OrderRepository for IOrderRepository) or after what distinguishes it (SqlOrderRepository), never with an Impl suffix. CA1711
NAM-025 DO keep generated code in files the analyzers recognize as generated (*.g.cs, *.Designer.cs or an // <auto-generated/> header) and never rename identifiers inside them to satisfy these naming rules. Manual
NAM-026 DO end the name of a DateTime that holds a UTC instant with Utc (CreatedUtc, expiresUtc); the names of DateTimeOffset values stay unchanged (VAR-040). Manual
NAM-030 DO name solutions, projects and assemblies <Company>.<Product>[.<Feature>] in PascalCase, with the solution named after the product (Contoso.Orders.sln, Contoso.Orders.Billing.csproj). Manual
NAM-031 DO name namespaces <Company>.<Product>[.<Feature>] in PascalCase, using a plural only for a segment that groups many types of one kind, and never use a type name as a namespace segment. IDE1006
NAM-032 DO make each source file's folder path, appended to the project's root namespace, equal the file's namespace (src/Contoso.Orders/Billing/Invoice.cs declares namespace Contoso.Orders.Billing;). IDE0130, ReSharper: CheckNamespace
NAM-033 DO name the file of a generic type after the type without its arity or type parameters (Result.cs holds Result<TValue>), and keep a generic and non-generic type of the same name in that one file. Manual
NAM-034 DO name the main file of a partial type <Type>.cs and every other part <Type>.<Role>.cs (Customer.cs, Customer.Validation.cs, OrderService.Logging.cs). Manual
NAM-035 DO keep a nested type in the file of its containing type and a file-local type in the one file that uses it, without separate files for either. Manual
NAM-036 DO name each unit-test project <ProjectUnderTest>.Tests and each integration-test project <ProjectUnderTest>.Integration.Tests, or place test projects under a tests/ folder, so the test-file section matches them. Manual

Words, acronyms and abbreviations

These rules apply to every identifier: how an acronym is capitalized, which words may be shortened, which characters are allowed, and which names clash.

NAM-010

DO write a two-letter acronym in PascalCase identifiers fully in upper case (IOStream, UIState) and an acronym of three or more letters with only its first letter capitalized (XmlReader, HttpClientFactory, JsonOptions).

✅ Correct

namespace Contoso.Orders;

public sealed class UIRegionBuilder
{
    public required string RegionName { get; init; }
}

public sealed class OrderXmlExporter
{
    public required string IOPath { get; init; }
}

❌ Incorrect — acronyms capitalized by the wrong length rule

namespace Contoso.Orders;

public sealed class OrderXMLExporter { } // three-letter acronym in capitals

public sealed class UiRegionBuilder { } // two-letter acronym not upper case

public sealed class HTTPRetryPolicy { } // four-letter acronym in capitals

Why: A fixed split at two letters lets a reader and a reviewer predict the name without looking it up: IOStream and XmlReader follow the pattern of the .NET libraries and of the Microsoft FDG. The Google guide treats every acronym as a word (Io, Ui); the FDG prescribes full capitals for two-letter acronyms.

Exceptions: Id and Ok are words, not acronyms (NAM-012).

Scope: Acronyms inside PascalCase identifiers (types, members, namespaces, constants) · Enforced: Manual · Sources: MS-FDG-CAPS, AV, GOOG, RS-NAMING

NAM-011

DO write an acronym that starts a camelCase identifier entirely in lower case, whatever its length (ioStream, xmlReader, httpClient, _uiState).

✅ Correct

public static string ExportOrder(Order order, Stream ioStream, System.Xml.XmlWriter xmlWriter)
{
    xmlWriter.WriteElementString("total", order.Total.ToString(CultureInfo.InvariantCulture));

    return ioStream.CanWrite ? "written" : "read-only";
}

❌ Incorrect — upper-case acronym at the start of a camelCase name, and a split acronym

public static string ExportOrder(
    Order order,
    Stream IOStream, // camelCase name starts with an upper-case acronym
    System.Xml.XmlWriter xMLWriter) => ""; // acronym split by a lower-case first letter

Why: A parameter or local starts with a lower-case letter so that it cannot be mistaken for a type or member. An acronym at the start follows the same rule: ioStream, never IOStream and never xMLWriter. IDE1006 reports the upper-case first letter of IOStream as a casing violation, but the acronym rule itself is reviewed.

Scope: Acronyms that start a camelCase identifier (parameters, locals, private field names after the prefix) · Enforced: Manual · Sources: MS-FDG-CAPS, MS-IDNAME

NAM-012

DO write Id and Ok as ordinary words (CustomerId, IsOk), closed compounds as one word (Email, Endpoint, Metadata, Callback) and the two-word terms UserName, FileName and LogOn with a capital on each word, never ID, OK, EMail, Username or Filename.

✅ Correct

namespace Contoso.Orders;

public sealed record CustomerContact(int CustomerId, string Email, string UserName);

❌ Incorrect — a different spelling for each of three terms

namespace Contoso.Orders;

public sealed record CustomerContact(
    int CustomerID, // ID is not an acronym
    string EMail, // Email is one word
    string Username); // the term is spelled UserName

Why: The Framework Design Guidelines fix the spelling of common terms: Id and Ok are written as ordinary words, closed compounds such as Email, Endpoint, Metadata and Callback are one word, and the two-word terms UserName, FileName and LogOn take a capital on each word. One spelling per term lets a reader and a code search predict the name: CustomerId everywhere, never CustomerID in one project and CustomerId in another. Id and Ok are words, not acronyms, so the two-letter acronym rule in NAM-010 does not apply to them.

Exceptions: Brand names keep the casing that the brand requires.

Scope: Compound words and the abbreviations Id and Ok in all identifiers · Enforced: Manual · Sources: MS-FDG-CAPS, AV

NAM-013

DO NOT shorten a word in an identifier except to the approved forms Id, Ok, Db, IO, UI, Xml, Json, Http, Url, Uri, the loop counters i, j, k, the catch variable ex, the event-data parameter e (NAM-145) and a one-letter parameter of a single-line lambda (NAM-232).

✅ Correct

private const decimal RatePerLine = 0.5m;
private const decimal RatePerKilometre = 0.1m;

public static decimal CalculateShippingCost(Order order, decimal distanceInKilometres) =>
    (order.Lines.Count * RatePerLine) + (distanceInKilometres * RatePerKilometre);

❌ Incorrect — abbreviated method and parameter names

private const decimal RatePerLine = 0.5m;
private const decimal RatePerKilometre = 0.1m;

public static decimal CalcShipCost( // abbreviated method name
    Order ord, // abbreviated parameter name
    decimal dist) // abbreviated parameter name
{
    return (ord.Lines.Count * RatePerLine) + (dist * RatePerKilometre);
}

Why: A shortened word makes the reader decode it, and two authors shorten the same word differently (Ord, Ordr, Ordr1). The list of approved forms is closed: to allow another abbreviation, change this rule.

Exceptions: The approved forms are Id, Ok, Db, IO, UI, Xml, Json, Http, Url, Uri, the loop counters i, j, k, the catch variable ex, the event-data parameter e (NAM-145) and a one-letter parameter of a single-line lambda (NAM-232).

Scope: Words in every identifier · Enforced: Manual · Sources: MS-FDG-GENERAL, MS-IDNAME, AV

NAM-014

DO write identifiers as English words spelled with the ASCII letters A-Z, a-z and digits only.

✅ Correct

namespace Contoso.Orders;

public static class InvoiceNumberGenerator
{
    public static string CreateNumber(int invoiceId) => $"INV-{invoiceId:D6}";
}

❌ Incorrect — a non-English word and a non-ASCII letter

namespace Contoso.Orders;

public static class RechnungsNummerGenerator // German words instead of English ones
{
    public static decimal GetCaféTotal() => 0m; // non-ASCII letter
}

Why: C# accepts letters from any script, but not every contributor can type or read them, and a name that needs a specific keyboard layout cannot be searched or typed by the whole team. English words with ASCII letters are the one set every team member can read, type and search.

Exceptions: String literals, comments and resource text are not identifiers; this rule does not apply to them.

Scope: All identifiers, including test and resource names · Enforced: Manual · Sources: AV, MS-IDNAME

NAM-015

DO NOT declare an identifier that needs the @ verbatim prefix, such as @class or @event, except in generated interop code that must mirror an external name.

✅ Correct

public static string DescribeCategory(string category) => category;

❌ Incorrect — a keyword used as a parameter name

public static string DescribeCategory(string @class) => @class; // keyword used as identifier

Why: An identifier with @ needs the prefix at every use, and the name stays reserved in the reader's mind. Choose a synonym (category, eventName) instead. CA1716 also reports keyword names, but it includes Visual Basic keywords such as Next and Step, so the shipped .editorconfig sets it to none.

Exceptions: Generated interop code that must mirror an external name (NAM-025).

Scope: Identifiers that match a C# keyword · Enforced: Manual · Config: dotnet_diagnostic.CA1716.severity · Sources: MS-FDG-GENERAL, MS-IDNAME

NAM-016

DO NOT write an underscore inside an identifier; the only underscores allowed are the single leading _ of a non-public instance field (a protected one included) or mutable static field, followed by camelCase (_orderCount, never _order_count, s_orderCount, t_depth or orderCount_s), the discard _ and the separators of test method names (TEST-011).

✅ Correct

namespace Contoso.Orders;

public sealed class OrderSummary
{
    private static int _ordersPlaced;
    private int _lineCount;

    public decimal OrderTotal { get; init; }

    public bool HasLines => _lineCount > 0;

    public void CountLine() => _lineCount++;

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

❌ Incorrect — an underscore inside a public name, snake_case after the _ prefix and a suffix after an underscore on a local

namespace Contoso.Orders;

public sealed class OrderSummary
{
    private static int _order_count; // snake_case after the prefix
    public decimal Order_Total { get; init; } // underscore inside a public name

    public static int NextNumber()
    {
        _order_count++;
        int orderCount_s = _order_count; // suffix after an underscore

        return orderCount_s;
    }
}

Why: No source allows an underscore after the prefix, so this rule extends MS-IDNAME and the Framework Design Guidelines. MS-IDNAME asks for camelCase after its _ prefix, and the guidelines ban underscores in names. The ban applies to everything after the prefix, so a name carries one _ and then camelCase: _orderCount, never _order_count or orderCount_s. The s_ and t_ prefixes that MS-IDNAME and dotnet/runtime prescribe are not used; static fields follow the ReSharper defaults: _camelCase for mutable ones, including [ThreadStatic], and PascalCase for static readonly ones (NAM-210, NAM-212). CA1707 reports externally visible (public and protected) names, and among fields only constants and static readonly fields. Test methods are the only public members that carry underscores (CA1707 is off in the test-file section of the .editorconfig). IDE1006 with word_separator = _ on the two camelCase styles (camel_case and underscore_camel_case) covers non-public instance and mutable static fields, parameters and locals. It reports a lower-case word after an inner underscore, as in _order_count ("These non-leading words must begin with an upper case letter: count"), so existing snake_case fields, parameters and locals produce IDE1006 warnings. IDE1006 also reports s_cache and t_depth as "Missing prefix: ''" on a mutable static field, and s_cache as "Prefix 's' is not expected" on a static readonly field. No shipped tool reports a capitalised word after an inner underscore (_max_Count, _order_Total), an inner underscore in a private or internal static readonly field (Shared_Client, because pascal_case has no word separator), non-public members such as Do_Work, or private constants such as Max_Count and MAX_ITEMS, so reviewers check them. A public instance field Order_Total gets no naming diagnostic either: the public field itself is reported by CA1051. A protected instance field in a public type is reported by CA1051 as well, in either name style; a leading _ on it breaks no naming diagnostic, and no shipped naming rule checks its style, so reviewers do. With StyleCop opted in, SA1308 reports s_ and t_ prefixes and SA1310 reports underscores in un-prefixed field names (TOOL-016).

Exceptions:

  • The single leading _ of a non-public instance field or mutable static field (NAM-200, NAM-210, NAM-212); the rest of the name stays camelCase.
  • The single leading _ of a protected or protected internal instance field, which NAM-203 accepts next to PascalCase.
  • The discard _.
  • The separators of test method names (TEST-011).
  • Generated code (NAM-025).
  • P/Invoke constants that must match native headers (NAM-206).

Scope: Every identifier (CA1707 checks externally visible names, among fields only constants and static readonly fields; IDE1006 checks non-public instance and mutable static fields, parameters and locals through the word separator) · Enforced: CA1707 for externally visible (public and protected) names, among fields only constants and static readonly fields; IDE1006 with the word separator for non-public instance and mutable static fields, parameters and locals. Reviewed (no shipped tool reports them): the name of a protected or protected internal instance field (either style is accepted, and no shipped naming rule checks them), a capitalised word after an inner underscore (_max_Count, _order_Total, local or parameter order_Total), an inner underscore in private and internal static readonly fields (Shared_Client, because pascal_case has no word separator), non-public members such as Do_Work, private constants such as Max_Count and MAX_ITEMS, and a public instance field Order_Total · Config: dotnet_naming_style.camel_case.word_separator, dotnet_naming_style.underscore_camel_case.word_separator · Sources: MS-FDG-CAPS, MS-FDG-GENERAL, MS-IDNAME, MS-IDE-NAMING, MS-CA, MS-TEST

NAM-017

DO NOT give two identifiers in the same scope names that differ only by letter case.

✅ Correct

namespace Contoso.Orders;

public sealed class InvoiceTotals
{
    public decimal Net { get; init; }

    public decimal Gross { get; init; }
}

❌ Incorrect — two members whose names differ only by case

namespace Contoso.Orders;

public sealed class InvoiceTotals // declares two members whose names differ only by case
{
    public decimal Total { get; init; }

    public decimal total() => Total; // differs only by case from Total
}

Why: Visual Basic and other case-insensitive languages cannot tell Total from total, so a public API that relies on case cannot be used from them. A reader can also take one name for the other. Rename one member to say what it does (GetTotal).

Scope: Identifiers in the same scope: members of one type, parameters of one method, types of one namespace · Enforced: CA1708 · Sources: MS-FDG-CAPS, MS-CA

Meaningful names

These rules fix the shapes of names that tell a reader what a value is: a Boolean, a collection, a quantity with a unit, a role instead of a number, or the default implementation of an interface.

NAM-020

DO name a Boolean variable, field or parameter as an affirmative statement that starts with is, has, can or should (isPaid, hasLines, canShip, _isClosed).

✅ Correct

public static bool CanShip(Order order)
{
    bool hasLines = order.Lines.Count > 0;
    bool isOpen = !order.IsShipped;

    return hasLines && isOpen;
}

❌ Incorrect — Boolean names that are not affirmative statements

public static bool CanShip(Order order)
{
    bool lines = order.Lines.Count > 0; // a noun, not a statement
    bool notShipped = !order.IsShipped; // negative name
    bool flag = lines && notShipped; // name does not say what true means

    return flag;
}

Why: A name that reads as a statement makes the condition read as a sentence: if (isPaid). A negative name forces a double negation in !notShipped, and a noun such as lines or a word such as flag does not say what true means. Boolean properties follow NAM-141 and Boolean-returning methods follow NAM-132.

Scope: Boolean fields, locals, parameters and constants (properties: NAM-141; methods: NAM-132) · Enforced: Manual · Sources: MS-FDG-MEMBERS, MS-FDG-PARAMDESIGN, AV

NAM-021

DO name a variable, field or parameter that holds a collection with a plural noun (orders, lines, _pendingOrders), not with a List, Array or Collection suffix.

✅ Correct

IReadOnlyList<OrderLine> lines = [new OrderLine("SKU-1", 2, 5m)];
decimal total = lines.Sum(line => line.Amount);
Console.WriteLine(total);

❌ Incorrect — a type suffix and a singular name for a collection

IReadOnlyList<OrderLine> lineList = [new OrderLine("SKU-1", 2, 5m)]; // type suffix in the name
IReadOnlyList<OrderLine> line = [new OrderLine("SKU-2", 1, 9.99m)]; // singular name for a collection

Why: A plural noun tells the reader that the value holds several items before they look at its type, and it survives a change of type from List<OrderLine> to IReadOnlyList<OrderLine> without a rename. A suffix such as List repeats what the declaration already says. Collection properties follow NAM-142.

Scope: Variables, fields and parameters that hold collections (properties: NAM-142) · Enforced: Manual · Sources: MS-FDG-MEMBERS, AV

NAM-022

DO put the unit at the end of the name of a numeric field, parameter, property or local that is not a TimeSpan (weightInKilograms, MaxPayloadBytes, distanceInKilometres).

✅ Correct

private const decimal RatePerKilogram = 0.2m;
private const decimal RatePerKilometre = 0.05m;

public static decimal EstimateShippingCost(decimal weightInKilograms, int distanceInKilometres) =>
    (weightInKilograms * RatePerKilogram) + (distanceInKilometres * RatePerKilometre);

❌ Incorrect — numeric parameters without a unit

private const decimal RatePerKilogram = 0.2m;
private const decimal RatePerKilometre = 0.05m;

public static decimal EstimateShippingCost(
    decimal weight, // unit missing
    int distance) // unit missing
{
    return (weight * RatePerKilogram) + (distance * RatePerKilometre);
}

Why: A bare number hides its unit, and a wrong unit is a silent defect: weight can mean grams or kilograms, distance can mean metres or kilometres. With the unit in the name, the call site states the unit and a reviewer can check it.

Exceptions: Durations use TimeSpan, which carries its unit in the type: write TimeSpan timeout, not int timeoutMs (VAR-043).

Scope: Numeric quantities with a unit (durations use TimeSpan, VAR-043) · Enforced: Manual · Sources: MS-DT, AV

NAM-023

DO NOT tell two names apart with a numeric suffix (order2, customer1, ProcessOrder2); name each after its role instead (originalOrder, updatedOrder).

✅ Correct

public static decimal GetTotalDifference(TimeProvider timeProvider)
{
    var originalOrder = new Order(7, timeProvider.GetUtcNow());
    var reorderedOrder = new Order(7, timeProvider.GetUtcNow());
    reorderedOrder.AddLine(new OrderLine("SKU-1", 2, 5m));

    return reorderedOrder.Total - originalOrder.Total;
}

❌ Incorrect — numeric suffixes instead of roles

public static decimal GetTotalDifference(TimeProvider timeProvider)
{
    var order1 = new Order(7, timeProvider.GetUtcNow()); // numeric suffix
    var order2 = new Order(7, timeProvider.GetUtcNow()); // numeric suffix

    return order2.Total - order1.Total;
}

Why: A numeric suffix says that two things differ but not how. A role name says it, so a reviewer can check each use of the variable against its role, and swapping the two is visible in the diff.

Exceptions: Digits that belong to the domain are not suffixes: Sha256Hash, Utf8Text, Int64Value.

Scope: Names of variables, members, types and test data · Enforced: Manual · Sources: AV, MS-FDG-GENERAL

NAM-024

DO name the default implementation of an interface after the interface without its I prefix (OrderRepository for IOrderRepository) or after what distinguishes it (SqlOrderRepository), never with an Impl suffix.

✅ Correct

namespace Contoso.Orders;

public interface IInvoiceStore { }

public sealed class SqlInvoiceStore : IInvoiceStore { }

❌ Incorrect — an Impl suffix

namespace Contoso.Orders;

public interface IInvoiceStore { }

public sealed class InvoiceStoreImpl : IInvoiceStore { } // Impl suffix

Why: Impl says that the class implements something, which the : IInvoiceStore clause already says. A name taken from the interface (InvoiceStore) or from what sets the class apart (SqlInvoiceStore) tells the reader something new. CA1711 reports the suffix on externally visible types.

Scope: Classes that implement an interface (the type that CA1711 checks for an Impl suffix) · Enforced: CA1711 · Sources: MS-FDG-TYPES, MS-CA, AV

NAM-025

DO keep generated code in files the analyzers recognize as generated (*.g.cs, *.Designer.cs or an // <auto-generated/> header) and never rename identifiers inside them to satisfy these naming rules.

✅ Correct

// <auto-generated/>
namespace Contoso.Orders;

public sealed partial class OrderDto
{
    public int OrderId { get; set; }
}

❌ Incorrect — header removed and a generated member renamed by hand

namespace Contoso.Orders; // header removed, so the naming rules now apply to this file

public sealed partial class OrderDto
{
    public int OrderId { get; set; } // generated name order_id renamed by hand, lost at the next generation
}

Why: Analyzers skip files marked as generated, so the naming rules do not apply to names that the generator fixes. A hand edit is overwritten at the next generation, and removing the header turns the rules on for code that nobody owns. The shipped .editorconfig sets generated_code = true only for files inside a Migrations folder, at any depth, whose names contain an underscore, end in .Designer.cs or end in ModelSnapshot.cs (DATA-006), so that a first dotnet ef migrations add builds without warnings; analyzers, security rules included, do not run on those files. A hand-written file in a Migrations folder with such a name is silenced as well, so give hand-written files there names without an underscore. Hand-written migration files named <timestamp>_<name>, as FluentMigrator and DbUp use, are treated as generated too, and the folder name is matched with its exact case (Migrations, not migrations). Everywhere else recognition relies on the file name and header convention above.

Scope: Generated source files (source generators, scaffolding, designers, migrations) · Enforced: Manual · Sources: MS-CFG, MS-IDNAME

NAM-026

DO end the name of a DateTime that holds a UTC instant with Utc (CreatedUtc, expiresUtc); the names of DateTimeOffset values stay unchanged (VAR-040).

✅ Correct

namespace Contoso.Orders;

public sealed class OrderRow // A boundary type, mapped from the columns of a table
{
    public DateTime PlacedUtc { get; init; } // A datetime column has no offset: the DateTime holds UTC and says so in its name

    public DateTimeOffset ShippedAt { get; init; } // DateTimeOffset: the offset is in the type
}

public static class OrderExpiry
{
    public static bool IsExpired(DateTime expiresUtc, TimeProvider timeProvider) =>
        expiresUtc <= timeProvider.GetUtcNow().UtcDateTime;
}

❌ Incorrect — a DateTime that holds UTC under a name that does not say so

namespace Contoso.Orders;

public sealed class OrderRow // A boundary type, mapped from the columns of a table
{
    public DateTime PlacedAt { get; init; } // holds UTC, but nothing in the name says so
}

public static class OrderExpiry
{
    public static bool IsExpired(DateTime expires, TimeProvider timeProvider) => // holds UTC, but nothing in the name says so
        expires <= timeProvider.GetUtcNow().UtcDateTime;
}

Why: A DateTime carries no offset, only a Kind of Utc, Local or Unspecified, and Kind is not visible where the value is used. Microsoft says to save and share DateTime data as UTC with Kind set to Utc; a name that ends in Utc makes that visible at the call site and in review, and a comparison between placedUtc and a local DateTime.Now stands out. A DateTimeOffset stores its offset in the value, so it needs no suffix. The Utc suffix on variable and property names is a house convention: the Microsoft documentation states the UTC practice, and the .NET API uses Utc inside member names such as UtcNow and UtcDateTime, but no Microsoft guideline asks for a suffix on your own names. No analyzer reads names for meaning, so this is a manual rule.

Exceptions:

  • A DateTime that does not hold a UTC instant (a local calendar time, or a value without a zone) does not get the suffix; prefer DateTimeOffset or DateOnly (VAR-040).
  • A name fixed by an external contract (an interface member, a serialized field, a database column) keeps that name; convert at the boundary.

Scope: Fields, properties, parameters and locals of type DateTime that hold a UTC instant · Enforced: Manual · Sources: MS-DT

Solutions, projects, namespaces and files

These rules name build artefacts and files: solution, project, assembly, namespace, source file and test project. The namespace casing and the folder match are checked by IDE1006 and IDE0130. The rest is reviewed.

NAM-030

DO name solutions, projects and assemblies <Company>.<Product>[.<Feature>] in PascalCase, with the solution named after the product (Contoso.Orders.sln, Contoso.Orders.Billing.csproj).

✅ Correct

Contoso.Orders.sln
src/
  Contoso.Orders/Contoso.Orders.csproj
  Contoso.Orders.Billing/Contoso.Orders.Billing.csproj

❌ Incorrect — no company or product prefix, and lower case with hyphens

OrdersSolution.sln // no company or product prefix
src/
  contoso-orders-billing/contoso-orders-billing.csproj // lower case with hyphens instead of PascalCase with dots

Why: The company and product prefix keeps assembly names unique when several packages share a feed, because two companies can both ship a Billing assembly. The project name is the default for the assembly name and for the root namespace, so one dotted name reaches all three (NAM-031).

Scope: Solution files, project files and assembly names · Enforced: Manual · Sources: MS-FDG-ASSEMBLIES, MS-IDNAME, AV

NAM-031

DO name namespaces <Company>.<Product>[.<Feature>] in PascalCase, using a plural only for a segment that groups many types of one kind, and never use a type name as a namespace segment.

✅ Correct

namespace Contoso.Orders.Billing;

public static class InvoiceCalculator
{
    public static decimal AddTax(decimal net, decimal taxRate) => net + (net * taxRate);
}

❌ Incorrect — namespace segments that are not PascalCase

namespace Contoso.orders.billing; // segments are not PascalCase

public static class InvoiceCalculator
{
    public static decimal AddTax(decimal net, decimal taxRate) => net + (net * taxRate);
}

❌ Incorrect — a type name and a plural feature name used as namespace segments

namespace Contoso.Orders.Order; // Order is a type in Contoso.Orders
namespace Contoso.Orders.Billings; // plural for a feature that does not group many types of one kind

Why: A namespace starts with the same segments as its assembly, so a reader can go from a using directive to the project. A segment that matches a type name makes the name ambiguous between the namespace and the type: namespace Contoso.Orders.Order; would make Order mean two things inside Contoso.Orders. The IDE1006 naming rule checks only the PascalCase part; reviewers check the plural and the type-name parts.

Scope: Namespace declarations · Enforced: IDE1006 · Config: dotnet_naming_rule.nam_031_namespaces.* · Sources: MS-FDG-NAMESPACES, MS-IDNAME, MS-IDE-NAMING, AV

NAM-032

DO make each source file's folder path, appended to the project's root namespace, equal the file's namespace (src/Contoso.Orders/Billing/Invoice.cs declares namespace Contoso.Orders.Billing;).

✅ Correct — folder layout

src/Contoso.Orders/            root namespace: Contoso.Orders
  Contoso.Orders.csproj
  Billing/
    InvoiceCalculator.cs       namespace Contoso.Orders.Billing;

✅ Correct — matching declaration in Billing/InvoiceCalculator.cs

namespace Contoso.Orders.Billing;

public static class InvoiceCalculator
{
    public static decimal AddTax(decimal net, decimal taxRate) => net + (net * taxRate);
}

❌ Incorrect — the file in Billing/ skips the root namespace

namespace Contoso.Billing; // does not match the folder: expected Contoso.Orders.Billing

public static class InvoiceCalculator
{
    public static decimal AddTax(decimal net, decimal taxRate) => net + (net * taxRate);
}

Why: When the namespace follows the folder path, a reader finds the file of Contoso.Orders.Billing.InvoiceCalculator from its full name, and moving a file without updating its namespace shows up as a warning. The root namespace is the project's RootNamespace, which defaults to the project name. IDE0130 checks the match, and ReSharper's CheckNamespace does the same in Rider and ReSharper.

Exceptions: Generated code and files linked from another project.

Scope: Folder structure of every project relative to its root namespace · Enforced: IDE0130, ReSharper: CheckNamespace · Config: dotnet_style_namespace_match_folder, resharper_check_namespace_highlighting · Sources: MS-IDE, MS-FDG-NAMESPACES, RS-I-CHECKNS

NAM-033

DO name the file of a generic type after the type without its arity or type parameters (Result.cs holds Result<TValue>), and keep a generic and non-generic type of the same name in that one file.

✅ Correct

src/Contoso.Orders/
  Result.cs    contains Result and Result<TValue>
  Pair.cs      contains Pair<TKey, TValue>

❌ Incorrect — type parameters or arity in the file name

Result{T}.cs // type parameters in the file name
Result`1.cs // arity in the file name
Pair{TKey,TValue}.cs // type parameters in the file name

Why: The characters < and > are not allowed in Windows file names, and the arity form (a backtick and a digit) needs quoting in many shells. Keeping Result and Result<TValue> in Result.cs also keeps the types that share a name together. This rule owns the file name of a generic type; FMT-064 and FMT-065 link here for it.

Scope: File names of generic types · Enforced: Manual · Sources: AV, SA

NAM-034

DO name the main file of a partial type <Type>.cs and every other part <Type>.<Role>.cs (Customer.cs, Customer.Validation.cs, OrderService.Logging.cs).

✅ Correct

src/Contoso.Orders/
  OrderService.cs
  OrderService.Logging.cs
  OrderService.Validation.cs

❌ Incorrect — a main file with a role, a numbered part and a part without a separator

src/Contoso.Orders/
  OrderService.Main.cs // main file carries a role; it is OrderService.cs
  OrderService2.cs // numbered part
  OrderServiceLogging.cs // role not separated by a dot

Why: OrderService.Logging.cs sorts next to OrderService.cs in a file listing and states what the part holds. A numbered part says nothing about its content, and without the dot the name could be a separate type. This rule owns the file names of partial types; FMT-065 links here for them.

Scope: File names of partial types · Enforced: Manual · Sources: AV

NAM-035

DO keep a nested type in the file of its containing type and a file-local type in the one file that uses it, without separate files for either.

✅ Correct

namespace Contoso.Orders;

public static class OrderImporter
{
    public static int CountFields(string line) => new CsvRow(line.Split(',')).Fields.Length + ImportCounter.HeaderRows;

    private sealed record CsvRow(string[] Fields);
}

file static class ImportCounter
{
    public const int HeaderRows = 1;
}

❌ Incorrect — a nested type split into its own file

src/Contoso.Orders/
  OrderImporter.cs
  OrderImporter.CsvRow.cs // nested type split into its own file

Why: A nested type is part of its container's design, and a file type is visible only inside its file. A separate file hides that link, and a nested type can only live in another file if the container becomes partial.

Scope: Nested types and file-local (file) types · Enforced: Manual · Sources: AV, SA

NAM-036

DO name each unit-test project <ProjectUnderTest>.Tests and each integration-test project <ProjectUnderTest>.Integration.Tests, or place test projects under a tests/ folder, so the test-file section matches them.

✅ Correct

tests/
  Contoso.Orders.Tests/Contoso.Orders.Tests.csproj
  Contoso.Orders.Integration.Tests/Contoso.Orders.Integration.Tests.csproj

❌ Incorrect — names and folders that the test-file section does not match

src/Contoso.Orders.IntegrationTests/ // name does not end in .Tests and the folder is not tests/
OrdersTestProject/ // no project-under-test prefix, name does not end in .Tests

Why: The test-file section of the shipped .editorconfig is [{**.Tests/**.cs,tests/**.cs}]. It relaxes CA1707 for test method names (NAM-016, TEST-011) and switches off the Async suffix rule and CA2007 for tests. A folder named Contoso.Orders.IntegrationTests matches neither pattern, so its test methods get CA1707 warnings. Only a project whose folder name ends in .Tests, or a top-level tests/ folder next to the root .editorconfig, is matched; a tests/ folder nested deeper is not. The common <Project>.IntegrationTests form falls outside both patterns for that reason.

Scope: Test projects (also drives the test-file section of .editorconfig) · Enforced: Manual · Sources: MS-TEST, AV

Sources

MS-IDNAME · MS-FDG-CAPS · MS-FDG-GENERAL · MS-FDG-ASSEMBLIES · MS-FDG-NAMESPACES · MS-FDG-TYPES · MS-FDG-MEMBERS · MS-FDG-PARAMDESIGN · MS-IDE · MS-IDE-NAMING · MS-CFG · MS-CA · MS-DT · MS-TEST · SA · AV · GOOG · RS-NAMING · RS-I-CHECKNS


Previous: Layout and Formatting · Home · Next: Naming Types and Members