C# Field Naming Guidelines

cnaming-conventions

I am going to be working on a bit of C# code on my own but I want to make sure that I follow the most widely accepted naming conventions in case I want to bring on other developers, release my code, or sell my code. Right now I am following the naming convention that Microsoft has set as they seem to be the most widely accepted. The one thing they don't mention though is naming for private fields. For the most part I have seen them named in camelCase like protected fields however that present me with an issue as parameter names should be in camelCase. Take the following constructor for example:

public GameItem(string baseName, string prefixName, string suffixName)
{
    //initialize code
}

Now if I use camelCase for the private fields too there is a naming conflict unless I use "this" in order to access the class fields (which I think is against most standards not to mention means more typing). One solution is to give the parameter a different name but that does not make logical sense to give the same data 2 different names. The only other solution that I know of that was common in C++ coding is giving private members an underscore at the beginning (_camelCase). Is that solution commonly accepted with C# coding? Is there another solution to this problem (like only using properties (which use PascalCase) to access fields, even in the class itself)?

Best Answer

_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.

Related Topic