📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you name things well in C#? What makes a name intention-revealing, which .NET naming conventions matter, and why should you avoid abbreviations and type names in identifiers?

Covers intention-revealing names, the .NET naming conventions (PascalCase, camelCase, I-prefix, Async suffix), and avoiding abbreviations, Hungarian notation and type names in identifiers.

Junior Theory Beginner clean-code code-quality conventions csharp editorconfig naming

🎯 Key points

  • Intention-revealing: the name says what and why, not how (activeCustomers vs list2)
  • Names scale with scope: i is fine in a 3-line loop, not as a field
  • Use the domain's language (ubiquitous language) agreed with the team and the business: Invoice, Refund, not Data, Item, Manager
  • PascalCase for types and members, camelCase for locals and parameters, _camelCase for private fields, I-prefix for interfaces
  • Async suffix on Task-returning methods; booleans as Is/Has/Can questions
  • No Hungarian notation or type names (strName, customerList) and no unclear abbreviations
  • Good names keep code readable for years: names are read in every call site, log and diff, comments are not
  • Enforce conventions with .editorconfig naming rules (IDE1006) rather than review comments

⏱ 30-second answer

A good name is intention-revealing: it tells the reader what something is and why it exists without making them read the implementation. overdueInvoices beats list2; IsEligibleForRefund() beats Check().

In C# follow the .NET conventions: PascalCase for types, methods and properties, camelCase for locals and parameters, _camelCase for private fields, I prefix on interfaces, Async suffix on Task-returning methods, and booleans phrased as questions (IsActive, HasLines). Avoid abbreviations (cust, amt) and type names in identifiers (customerList, strName): the compiler already knows the type and the name goes stale when the type changes. Use the business's words. The trade-off is length: names should grow with scope, so i is fine in a three-line loop but not as a field.

🗣 Full answer (senior)

How I would answer this in an interview

"A good name answers the questions a reader would otherwise have to read the code for: what is this, and why does it exist. So overdueInvoices instead of list2, CalculateGst instead of DoCalc, IsEligibleForRefund instead of Check. I also use the business's language: if finance calls it a credit note, the class is CreditNote, not NegativeInvoice, because then conversations with the product owner map straight onto the code.

In C# there are well-established conventions and I just follow them so nobody has to think: PascalCase for types, methods, properties and constants, camelCase for parameters and locals, underscore-camelCase for private fields, an I on interfaces, Async on methods that return a Task, and booleans read as yes/no questions like IsActive or HasOutstandingBalance. Methods are verbs, classes are nouns. And I avoid abbreviations and type names in identifiers: customerList becomes wrong the day someone changes it to an IReadOnlyCollection, and amt saves three characters at the cost of every reader decoding it.

The mistake I see is vague names like Manager, Helper, Processor or Data. They usually mean the class has no clear responsibility, so a naming problem is often a design problem. The best tool for naming is the rename refactoring: if a better name appears, change it immediately."


.NET naming conventions

Element Convention Example
Class, record, struct, enum PascalCase noun OrderTotalCalculator
Interface I + PascalCase IOrderRepository
Method PascalCase verb CalculateTotal, SendInvoiceAsync
Property PascalCase noun or adjective Total, IsPaid
Parameter, local camelCase orderId, overdueInvoices
Private field _camelCase _repository
Constant PascalCase MaxRetryCount
Generic type parameter T or T + descriptor TEntity, TKey
Async method Async suffix GetOrderAsync

Good vs poor names

Poor Better Why
d daysSinceLastOrder Says what and the unit
customerList activeCustomers Says which ones, not the type
Check(o) IsEligibleForFreeShipping(order) States the question asked
OrderManager OrderPlacementService Names the responsibility
flag hasUnpaidInvoices Boolean reads as a question
ProcessData() ImportBankStatement() Domain verb and noun

Scope rule

The wider the scope, the more descriptive the name. Loop counters and lambda parameters (orders.Where(o => o.IsPaid)) can be short because the context is a single line; public API members must be self-explanatory because readers see them far from their definition.

Production example

In a billing service, a field called amount was sometimes cents and sometimes dollars depending on the caller. Renaming to amountInCents and amountInDollars (and later to a Money value object) exposed four call sites passing the wrong unit, one of which had been overcharging a small set of customers by a factor of 100 on refunds.

🔍 What the interviewer is checking

Checks the candidate writes names for the reader, knows the .NET conventions, and sees naming as part of design.

Green flags

  • Gives before/after examples with domain words
  • Knows PascalCase/camelCase/_camelCase, I-prefix and Async suffix
  • Links vague names to unclear responsibilities
  • Mentions enforcing conventions with editorconfig

Red flags

  • Uses Hungarian notation or type suffixes as a habit
  • Thinks naming is purely cosmetic
  • Can't name the casing conventions

📚 Learn in depth

1. Why names matter more than comments

A name is read every time a symbol is used: in IntelliSense, call stacks, logs and diffs. A comment is read only at the definition, and nothing forces it to stay correct. So the name is the most-read documentation in the codebase.

  Definition:   var x = GetOverdue();      // x = invoices over 30 days
  Use site 1:   foreach (var i in x) ...   // reader must scroll up
  Use site 2:   Send(x);                   // still no idea

2. Intention, not implementation

Name things by what they mean, not how they are built. invoiceCache describes mechanism; recentlyViewedInvoices describes meaning. When the implementation changes from a dictionary to a HybridCache, the second name stays correct.

3. Ubiquitous language

Domain-driven design calls the shared vocabulary between developers and the business the ubiquitous language. If the code says Customer but the business says Account Holder, every conversation needs translation and bugs hide in the gaps. Prefer the business term, and keep one term per concept across the codebase.

4. Conventions and how the tooling enforces them

The .NET Framework Design Guidelines define the casing conventions. In a team, encode them in .editorconfig naming rules so the IDE (rule IDE1006) flags violations and dotnet format can fix them:

  .editorconfig  -->  Roslyn IDE analysers  -->  squiggles in IDE
                                           -->  build warnings (EnforceCodeStyleInBuild)
                                           -->  dotnet format in CI

5. Smells hidden in names

  • Manager, Helper, Utils, Processor: the class does several unrelated things.
  • And in a method name (ValidateAndSave): two responsibilities.
  • Numbered names (order2, HandleV2): an unclear concept.
  • Negated booleans (isNotInvalid): double negatives in conditions.

Try it yourself

  1. Add an .editorconfig naming rule requiring _camelCase private fields and set EnforceCodeStyleInBuild to true; break it and build.
  2. Find every class ending in Helper or Manager in a repo and list what each actually does.
  3. Use the IDE rename refactoring (F2 / Ctrl+R,R) on a public member and check it updates all references.
  4. Rewrite five boolean conditions so they read as plain English when spoken aloud.

💻 Code

Same logic, before and after renaming. Nothing else changed.

// Before
public class InvMgr(IInvRepo r)
{
    public async Task<List<Inv>> Get(int d, bool f)
    {
        var lst = await r.GetAll();
        var res = new List<Inv>();
        foreach (var i in lst)
            if ((DateTime.UtcNow - i.Dt).TotalDays > d && (!f || i.Amt > 0)) res.Add(i);
        return res;
    }
}
// After
namespace Billing.Invoices;

public sealed class OverdueInvoiceFinder(IInvoiceRepository invoices, TimeProvider clock)
{
    public async Task<IReadOnlyList<Invoice>> FindOverdueAsync(
        int daysPastDue, bool excludeZeroBalance, CancellationToken cancellationToken)
    {
        var allInvoices = await invoices.GetAllAsync(cancellationToken);
        var today = clock.GetUtcNow();

        return allInvoices
            .Where(invoice => (today - invoice.IssuedAt).TotalDays > daysPastDue)
            .Where(invoice => !excludeZeroBalance || invoice.OutstandingBalance > 0)
            .ToList();
    }
}

public interface IInvoiceRepository
{
    Task<IReadOnlyList<Invoice>> GetAllAsync(CancellationToken cancellationToken);
}

public sealed record Invoice(Guid Id, DateTimeOffset IssuedAt, decimal OutstandingBalance);
# .editorconfig: enforce _camelCase private fields
[*.cs]
dotnet_naming_rule.private_fields_underscore.symbols = private_fields
dotnet_naming_rule.private_fields_underscore.style = underscore_camel
dotnet_naming_rule.private_fields_underscore.severity = warning
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
dotnet_naming_style.underscore_camel.required_prefix = _
dotnet_naming_style.underscore_camel.capitalization = camel_case

⚠ Common mistakes

  • Mistake: Putting the type in the name (customerList, strName, iCount). Why it is wrong: the compiler and IDE already show the type, and the name becomes a lie when the type changes. Instead: name the meaning: activeCustomers, displayName.
  • Mistake: Abbreviating (cust, amt, calcTot). Why it is wrong: every reader decodes it, and abbreviations differ between people. Instead: spell it out; IntelliSense does the typing.
  • Mistake: Generic class names like Manager, Helper, Utils. Why it is wrong: they attract unrelated code and hide a missing responsibility. Instead: name the specific job (InvoiceNumberGenerator).
  • Mistake: Leaving off the Async suffix on Task-returning methods. Why it is wrong: callers miss that it must be awaited, which leads to fire-and-forget bugs. Instead: GetOrderAsync, except for controller actions and event handlers where conventions differ.
  • Mistake: Boolean names that don't read as questions, or negated ones (notValid). Why it is wrong: if (!notValid) is a double negative. Instead: IsValid, HasLines, CanBeRefunded.
  • Mistake: Using different words for the same concept (Client, Customer, Account). Why it is wrong: readers assume different words mean different things. Instead: pick one term per concept, ideally the business's.
  • Mistake: Very long names for very local things. Why it is wrong: indexOfTheCurrentOrderLineBeingProcessed hurts as much as x. Instead: scale the name to its scope.

🏛 Senior insight: trade-offs

Naming is the cheapest design tool you have. When a good name won't come, that is usually a signal that the thing does too much or that the team doesn't share a vocabulary for the concept. Seniors treat that as a design conversation (often with the product owner) rather than picking Manager and moving on.

The framework gives you the enforcement: .editorconfig naming rules, IDE1006 and dotnet format. Use them so naming conventions never come up in review, and spend review comments on naming meaning.

Choice When it fits Cost When not to
Short names (i, o) Lambdas, tiny loops None Fields, public members, long methods
Domain terms Business logic Need to learn the domain Generic infrastructure code
Technical terms (Cache, Factory) Infrastructure, framework glue Leaks mechanism Core domain types
Rename now Name is misleading Small diff, IDE does it Public API used by other teams: plan a deprecation instead

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions names that don't surprise the reader Why: Checks they apply least astonishment to API naming
    How to answer

    The principle of least astonishment says code should behave the way a reasonable user expects from its name, signature and context. In C# that means following .NET conventions: a TryParse method returns bool and never throws for bad input, an ...Async method returns a task and accepts a CancellationToken as its last parameter, properties are cheap and have no side effects, and Equals, GetHashCode and == agree. Surprises such as a GetUser that creates a user, or a property that makes a network call, cause bugs because callers rely on the convention rather than reading the implementation.

  2. When: Candidate mentions enforcing naming conventions Why: Checks they know how editorconfig naming rules work in the build
    How to answer

    I commit an .editorconfig at the repo root with root = true. It holds formatting (indentation, new lines), .NET code style preferences such as file-scoped namespaces, and severities for analyser and code style rules via dotnet_diagnostic.<id>.severity. Visual Studio, VS Code and Rider all read it, so style no longer depends on the editor. To enforce it, I set EnforceCodeStyleInBuild so IDE rules run during dotnet build, and run dotnet format --verify-no-changes in CI.

↩ Usually asked after

More in Clean Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me