C# Field Naming Guidelines?

_camelCase for fields is common from what I’ve seen (it’s what we use at our place and Microsoft prefer for the .NET Runtime).

My personal justification for using this standard is that is is easier to type _ to identify a private field than this.

For example:

void Foo(String a, String b)
{
    _a = a;
    _b = b;
}

Versus

void Foo(String a, String b)
{
    this.a = a;
    this.b = b;
}

I find the first much easier to type and it prevents me from ever accidentally assigning to the parameter called a instead of this.a.
This is reinforced by a Code Analysis Maintainability Rule that states:

  • CA1500 Variable names should not match field names.

My other reason, is that this. is optional (Visual Studio / Code prompts you to remove them) if it doesn’t collide with a local variable or parameter name, making knowing which variable you are using harder. If you have an _ at the start of all private fields, then you always know which is a field and which is has local scope.

Leave a Comment