views:

462

answers:

9

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?

+5  A: 

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

Justin Niessner
+1 for the adaptation to the team standards.
m_oLogin
+4  A: 

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://www.irritatedvowel.com/Programming/Standards.aspx

DanM
It's not a violation on the updated .Net design guidelines.
JaredPar
@Jared, thanks, can you provide a reference for this? I'm not seeing it in this area of the documentation: http://msdn.microsoft.com/en-us/library/xzf533w0%28VS.71%29.aspx
DanM
@DanM, Try the following link. Notice that the guidelines only cover the naming of public and protected members. http://msdn.microsoft.com/en-us/library/ms229012.aspx
JaredPar
@Jared, I still see no mention of underlines either way. So, maybe Microsoft is trying to stay agnostic on the issue?
DanM
@DanM, essentially yes they are remaining indifferent. IIRC they originally contained language prohibiting it but it was removed in the second version due to the disagreement on the issue. The predominant pattern in the BCL is a form of prefix with `_` appearing to have an edge so I choose that route.
JaredPar
The refactoring option to expose a private field as a public property takes a name like _portNumber and exposes it as PortNumber. In other words, it recognizes and removes the underbar. On the other hand, a Hungarian prefix would not only violate standards, it wouldn't work right. If it were m_portNumber, it would become MPortNumber.
Steven Sudit
@Steven, and `m_portNumber` is not only ugly, it harms readability. Basically, the `m` part gets in the way of seeing the `portNumber` part.
DanM
@DanM: My problem with it is that it's HalfGarian. The prefix comes from one naming convention, the body from another. It makes my brain go in two directions at once, which is very bad, since it has enough trouble going in even one direction.
Steven Sudit
+7  A: 

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.

JaredPar
I didn't know they changed the conventions.
Joan Venge
Could you post a link to the ".Net framework guidelines" that you've mentioned? I know of the two "Design Guidelines for..." MSDN articles, but as far as I can tell they don't mention private fields anywhere..
stmax
+1  A: 

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

Otávio Décio
This is what I do.
Joan Venge
...and yet ReSharper will prompt you to remove the redundant "this."
TrueWill
I find that overly verbose. Something like `_portNumber` seems perfectly clear, whereas `this.portNumber` adds length without clarity, and looks too much like Java style. Aesthetics aside, the `this.` is syntactically redundant in these cases.
Steven Sudit
I personally never use 'this'. It is certainly redundant most of the time.
Otávio Décio
+1  A: 

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.

LorenVS
The BEST way is what the programming team has agreed to follow.
Steven Sudit
A: 

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.

Task
Thanks, what's the conventions for constant/static readonly fields?
Joan Venge
This is incorrect as there are no official Microsoft standard coding guidelines. The closest item is the .Net framework design guidelines which says nothing about the naming of private fields. StyleCop chooses the convention of non-prefixed private fields but it is not an MS standard.
JaredPar
Actually, you are incorrect. StyleCop IS the MS standard: http://blogs.msdn.com/sourceanalysis/archive/2008/05/23/announcing-the-release-of-microsoft-source-analysis.aspx
Task
@Task: Jared is from Microsoft. Also, the link you provided says "has been used for many years now to help teams enforce a common set of best practices". It doesn't say "used by all teams".
John Saunders
"... the majority of teams using this tool within Microsoft have found that after a short adjustment period, they... began to find it difficult to read code not written in this style." Wurst sales pitch evur!
Daniel Earwicker
I know, I just thought it was kind of funny that one person from MS says they've got a common style and another doesn't. 8 ) It's a big company, I wouldn't expect everyone to code the same way. Nonetheless, this is the tool that they've published and that they use. Whether or not it represents "the official guidelines that all should follow", it's the best they've come up with and the closest thing to.
Task
+1  A: 

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.

Chris S
Thanks but how does underscores prevent stackoverflows?
Joan Venge
I've updated with a link. It may seem a bit contrived but I have been a victim of it a few times
Chris S
@Joan: I think he means not having the Foo property reference "Foo" when it should be referencing "_foo".
John Saunders
Ok thanks, got it now.
Joan Venge
I lost the changes to my answer, but essentially @John yes as stupid as it sounds, I've been stung by referencing the pascal case property instead of the camel case a few times in the past (before I switched to underscores).
Chris S
This is what I was talking about: http://stackoverflow.com/questions/241134/what-is-the-worst-c-net-gotcha/241194#241194
Chris S
+1  A: 

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.

stmax
@stmax: my understanding is that StyleCop was developed by one team to uphold its standards. I do not believe it represents a well-researched, company-wide set of best practices, as FxCop does.
John Saunders
+2  A: 
Claudio Redi