开发者

C# Field Naming Guidelines?

开发者 https://www.devze.com 2023-01-06 08:46 出处:网络
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, o

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). O开发者_如何学JAVAne 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)?


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


Follow the Microsoft Naming Guidelines. The guidelines for field usage indicate that it should be camelCase and not be prefixed. Note that the general rule is no prefix; the specific rule is not to prefix to distinguish between static and non-static fields.

Do not apply a prefix to field names or static field names. Specifically, do not apply a prefix to a field name to distinguish between static and nonstatic fields. For example, applying a g_ or s_ prefix is incorrect.

and (from General Naming Conventions)

Do not use underscores, hyphens, or any other nonalphanumeric characters.

EDIT: I will note that the docs are not specific with regard to private fields but indicate that protected fields should be camelCase only. I suppose you could infer from this that any convention for private fields is acceptable. Certainly public static fields differ from protected (they are capitalized). My personal opinion is that protected/private are not sufficiently different in scope to warrant a difference in naming convention, especially as all you seem to want to do is differentiate them from parameters. That is, if you follow the guidelines for protected fields, you'd have to treat them differently in this respect than private fields in order to distinguish them from parameters. I use this when referring to class members within the class to make the distinction clear.

EDIT 2

I've adopted the convention used at my current job, which is to prefix private instance variables with an underscore and generally only expose protected instance variables as properties using PascalCase (typically autoproperties). It wasn't my personal preference but it's one that I've become comfortable with and probably will follow until something better comes along.


Generally there are two widely used ways to name fields (always using camelCase):

Using an underscore prefix

void F(String someValue) {
  _someValue = someValue;
}

Using this. to access the field and avoid name conflicts

void F(String someValue) {
  this.someValue = someValue;
}

Personally I prefer the later, but I will use whatever convention is set forth by the organization I work for.


Short answer: use _privateField, i.e. use leading underscore for private fields.

Long answer: here goes...

Long long ago, Microsoft used to suggest using camelCase for fields. See here. Note when that document was created, 10/22/2008. Pretty ancient.

Recent code base of Microsoft however depicts a different picture.

  1. Take a look at the C# Coding style of .NET Runtime GitHub repository. #3 is the point under discussion. Here is the relevant part

    We use _camelCase for internal and private fields and use readonly where possible.

  2. Also take a look at Coding style of Roslyn repository that specifically says that it follows the conventions of .NET Runtime.
  3. Take yet another look at the .NET Standard contributing page, which also says (at least for now) to follow the same guide as .NET CoreFX, which was a precursor to .NET Runtime.
  4. Prior to consolidation, CoreCLR also suggested following the same guide as CoreFX.
  5. Even WinForms repo speaks of using this same standard.
  6. I think I have said enough. So, to conclude, if you want to follow the guide that Microsoft suggests, I think you know what to do; use leading underscore for private fields like this: _privateField.

My opinion: I too personally prefer leading underscore for my private fields - makes it very easily distinguishable, without needing the this.


In our shop, we started our first C# project using Microsoft's suggested guideline for private members, i.e.

camelCaseFieldName

But we soon ran into confusion between private members and parameters, and switched to

_camelCaseFieldName

which has worked much better for us.

A private member usually has a state that persists outside of a method call - the leading underscore tends to remind you of that.

Also note that using AutoVariable syntax for properties can minimize the need for private backing fields, i.e.

public int PascalCaseFieldName { get; set;}

For a nice concise set of standards that (mostly) follow the MS guidelines, check out net-naming-conventions-and-programming-standards---best-practices


As it was mentioned, Microsoft Naming Guidelines dose not cover private fields and local variable naming. And you don't find consistency within Microsoft itself. If you generate class or Disposable pattern in Visual Studio it will create something like

public MyClass(int value)
{
    this.value = value;
}

or

private bool disposedValue = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
    if (!disposedValue)
    {
        ...
    }
}

Fortunately more and more code was opened by Microsoft, so let's take a look a their repos, e.g. ASP.NET Core MVC

private readonly IControllerActivator _controllerActivator;
private readonly IControllerPropertyActivator[] _propertyActivators;

Or .NET Core

private T[] _array;

You may say, that it's not actually Microsoft, but .NET Foundation. Fair enough, let's take a look at Microsoft repos:

private readonly MetricSeries zeroDimSeries;

But here is ancient Microsoft implementation of MVC

private IActionInvoker _actionInvoker;

So there is not any common practice or official guideline regarding private fields naming. Just choose one you prefer and stick to it.


The most important thing is to pick one standard and stick with it. Check out iDesign's C# Coding Standard at IDesign (it's a link on the right side). It's a great document that covers things like naming guidelines. They recommend using camel case for both local variables and method arguments.


Philips Healtcare C# Coding Standard

MSDN - Eric Gunnerson

Edit: I use "this" keyword to access non-static members in C# and Java.


We use StyleCop to force consistency throughout our code. StyleCop is used within Microsoft enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code.

You can run StyleCop at build time and have it generate warnings for style violations.

To answer your specific question, private fields should be in camelCase and prefixed with "this".


Following Microsoft's naming conventions, private fields should be prefixed with an underscore.

For example:

private int _myValue;

Good luck!


The convention I use to distinguish between private class variables and method parameters is:

private string baseName;
private string prefixName;
private string suffixName;

public GameItem(string baseName, string prefixName, string suffixName)
{
    this.baseName = baseName;
    this.prefixName = prefixName;
    this.suffixName = suffixName;
}


I too had doubts about this and then I decided check github codes of Microsoft. Almost every source code I've looked at had underscore usage for private fields.

https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/ document does not seem to mention about this usage.


Have a look at ReSharper. It will underline all the places where your names do not confirm to ordinary guidelines, and you can customize it. Plus, of course there's loads and loads of other productivity enhancements.


I do this; it's pretty much in line with MSDN.

class MyClass : MyBaseClass, IMyInterface
{
    public event EventHandler MyEvent;
    int m_MyField = 1;
    int MyProperty {
        get {
            return m_MyField;
        }
        set {
            m_MyField = value;
        }
    }

    void MyMethod(int myParameter) {
        int _MyLocalVaraible = myParameter;
        MyProperty = _MyLocalVaraible;
        MyEvent(this, EventArgs.Empty);
    }
}

Here's a little more detail: http://jerrytech.blogspot.com/2009/09/simple-c-naming-convention.html


I've done much more with VB than C#, so I guess I carry over some practices (prejudices?) from the former to the latter.

I like the private fields of properties to have a leading underscore - especially in C# due to the case-sensitivity (whose idea was that anyway?) And I prefix module-/class-wide variables with "m" as well to reinforce their scope.

If you don't like that, you're really not gonna like this: I generally use type prefixes as well (except for property fields) - "o" for Object, "s" for String, "i" for Integer, etc.

I can't really defend this with a peer-reviewed paper or anything but it works for us and means we're not tripped up by casing or field/parameter confusion.

So ...

Class MyClass

    Private msClassVariable  As String = ""

    Private _classProperty As Integer = 0
    Property Readonly ClassProperty() As Integer
        Get
            Return _classProperty
        End Get
    End Property

    Sub New()

        Dim bLocalVariable As Boolean = False
        if _classProperty < 0 Then _classProperty = 0
        msClassVariable  = _classProperty.ToString()
        bLocalVariable = _classProperty > 0
    End Sub

End Class


Personally, I hack the parameter names by the prefix "the" such as theSamplingRate. For me, it makes perfect sense :)


private string baseName; 
private string prefixName; 
private string suffixName; 

public GameItem(string _baseName, string _prefixName, string _suffixName) 
{ 
    this.baseName = _baseName; 
    this.prefixName = _prefixName; 
    this.suffixName = _suffixName; 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消