Naming conventions for private members of .NET typ

2020-05-19 07:30发布

问题:

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 7 years ago.

Normally when I have a private field inside a class or a struct, I use camelCasing, so it would be obvious that it's indeed private when you see the name of it, but in some of my colleagues' C# code, I see that they use m_ mostly or sometimes _, like there is some sort of convention.

Aren't .NET naming conventions prevent you from using underscores for member names?

And when you mention the MS naming conventions or what not, they tell you theirs is the best way, but don't explain the reasoning behind it.

Also when I am the owner of some code, where I clearly use camelCasing for private members, when they have to make a minor modification to the code, they stick in their conventions instead of following whatever conventions are there.

Is this a controversy?

回答1:

Technically, underscores are a violation of .NET conventions (or at least used to be -- see comment thread), but Microsoft programmers themselves often use underscores, and many examples in the documentation use underscores. I think it's very helpful to be able to see at a glance which variables are member variables (fields) and which are local. The underscore really helps with this. It also nicely separates private member variables from local variables in intellisense.

Please see this very useful page for .NET naming conventions:

http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices

And here's a page with Microsoft's official recommendations:

https://msdn.microsoft.com/en-us/library/ms229045%28v=vs.110%29.aspx



回答2:

The .Net framework guidelines allow for a _ or m_ prefix on private field names because the provide no guidance on private fields. If you look at the BCL in reflector you'll notice a prefix is the most prevalent pattern.

The Reference page for naming fields is located here. Notice the guidelines only specify usage for public and protected fields. Private fields are simply not covered.



回答3:

I typically prefix private member variables with an underscore.

It just makes them easier to spot when you're trying to read the code and it's allowed by the Microsoft Guidelines:

public class Something
{
    private string _someString = "";

    public string SomeString
    {
        get
        {
            return _someString;
        }
        set
        {
            // Some validation
            _someString = value;
        }
    }
}

Like others have said, the more important thing is to be consistent. If you're on a team that has a coding standard that does things the m_ way, don't try to be a rebel and do yours another. It will just make things more difficult for everybody else.



回答4:

well, microsoft is not taking part for any of the 2 options. If on Visual Studio you encapsulate a field using "refactor->Encapsulate Field..." for

private string _myVar

and

private string myVar

both of them generates a propery like this

public string MyVar
{
    get { return myVar; }
    set { myVar = value; }
}

So for microsoft it's the same :-) It's only a question of reaching an agreement with the development team so everyone uses the same approach.

Normally I never use private fields except very specific situations. I encapsulate private fields with protected properties. Better for inheritance and more clear IMHO.



回答5:

Even in the BCL you see a lot of inconsistency with naming conventions, some classes have "_", some "m_" and some just the pascal case version of the property.

Underscore is good because you prevent accidental stackoverflows, although more recent versions of Visual Studio warn you about this anyway. They also appear first in your intellisense, avoiding the need to riddle your code with this.someProperty or search through the entire list.

As long as the team agrees on one standard it doesn't make a whole lot of difference, but having used underscores for 5+ years I personally wouldn't want to return back to the alternatives.

If you own the codebase and maintain it, I would insist they use your standards. If they don't then simple refactor it combined with a polite email why you've done it.



回答6:

Please see the last paragraph of the MS Field Usage Guidelines.

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.



回答7:

No conventions prevent you from using valid identifier names. The important thing is to be consistent. I use "_" for all private variables, although the "right way" (for example ReSharper) seems to want you to declare them starting with a lowercase letter and differentiate between parameters and members trough the use of "this."



回答8:

I don't really believe there is any BEST way to case variables and methods. What matters is that you and your team are consistent. The .NET naming conventions are great the way Microsoft specifies them, but some people prefer other conventions...

As a personal aside, I tent to prefix private variables and methods with "_" and then camel casing, protected variables and methods in camel casing and public variables and methods with pascal casing, but that is just me.



回答9:

There are two MSDN articles (here and here) about design guidelines that also contain naming conventions. Too bad they are restricted to "publically visible" things. They don't offer guidelines for naming non-public things and as far as I know Microsoft doesn't provide official naming guidelines for non-publics.

StyleCop (a Microsoft tool) is against using underscores in names. Two reasons I have heard from developers why they prefer to use the underscore:

  • it clearly marks non-public members (type _ and intellisense will show you all the non-publics).
  • it prevents conflicts between local variables (which are often also written in camelCase), method parameters and non-public fields.

IMO both are a good reason to use the underscore, however I don't like how it makes my code look so I don't use it either. I prefer to use only camelCase when possible and I add a this. in case of conflicts with local variables or method parameters.

We simply try to keep the coding style consistent within the team and project.



回答10:

Yes, the naming convention enforced by StyleCop (which enforces the MS coding rules) is 'no underscores, camel case' for private instance fields.

It is of note that constant/static readonly fields have the 'Pascal case' naming convention (must begin with uppercase but not be screaming caps).

The other naming conventions are holdovers from C++ style, which was the initial style used to code C# in since that's where the C# team came from.

Important Note: Whether or not you use this coding style is entirely up to the development team. It's far more important that everyone on the team use the same style than that any particular style be used.
OTOH, MS chose this style after much deliberation, so I use it as a tiebreaker. If there's no particular reason to go one way or another with a coding style, I go the way StyleCop goes.