Naming Conventions for C#

I’m a firm supporter of coding conventions (at least of my coding conventions).

Software factories [^] [^] [^] and other code generation tools have been taking care of writing the tedious (and, sometimes, ugly) code but, at some point, some code must be written and read by human developers. That’s why (in my opinion) the way the code is written is as much important as the language it is written in.

There are several resources about coding conventions for the .NET framework:

I haven’t read Brad and Krzysztof‘s book (yet), but I’ve read MSDN Library‘s guidelines and Juval‘s document and watched Krzysztof‘s presentation.

I have to disagree with Microsoft’s position about naming conventions of private members. In an enterprise as big as Microsoft projects start and end, people move between teams and every time someone changes team he/she is faced with the possibility of having to learn and adapt to a new set of naming conventions for private members.

IDesign goes one step further on defining naming conventions for private members. I just don’t like the convention they used. What’s the point of prefixing private member fields (not variables as in their document) with m_? What does it mean? Member? If it’s not a local method variable or a method parameter it’s a member.

Some just prefix with _. Once again, why? What does that mean?

The only reason I can find for this prefixing practice is lost in the old days of colorless IDEs, printers and books. With colorful IDEs like Visual Studio 2005 you just need to qualify instance member fields with the this (Me for Visual Basic) keyword and static (Shared in Visual Basic) member fields with (lacking of a better solution) the class name.

Lets pretend for a moment that I’m one of the prefixes. How would I do it?

  • i_camelCase for private instance members.
  • s_camelCase for private static members.
  • c_camelCase for private constants.

Why stop there? Let’s also prefix method variables:

  • v_camelCase for method variables.

Now I’m on a roll. Let’s prefix method parameters:

  • i_camelCase for input parameters.
  • o_camelCase for output parameters.
  • r_camelCase for by reference parameters.

The next step would be to go Hungarian and add type information to the names, right? No. Let’s stop here and get in the right track.

My Naming Conventions for C#

I Find that keeping naming conventions as simple as possible is the best way use and validate them.

  1. Pascal casing for any class/struct member (constants, fields, properties, methods, events) except for private fields.
  2. Camel casing for private fields and method/property parameters and variables.
  3. Prefix interface names with I (IAccountService).
  4. Prefix type parameter names with T (TKey, TValue).
  5. Suffix type with meaningful names for its purpose (AccountService, InvalidAccountException, MustVerifyAccountAttribute, FromAccountTextBox).
  6. Method names must reflect what they are supposed to do. Methods always do something, so they must start with a verb. (GetAccountInformation, UploadFile)
  7. Names must be descriptive. Abbreviations should not be used. Hungarian notation should not be used. Single name variables should not be used.
  8. Language keywords should be used instead of type names (string instead of System.String, int instead of System.Int32, etc.).
  9. Business relatad names should reflect business entities or actions, and in the business’ language (GetContaFromDataBase, ContaInválidaException, ValidarContaAttribute).
  10. Underscores should not be used. Camel casing should be used to separate words.
  11. Acronyms should be treated as a single word. Just to be compliant with Microsoft, for acronyms with less than three letters, all letters should be upper case.
This entry was posted in 2666, 2667, 2671, 2672, 2673, 2675, 2676, 2677, 6617. Bookmark the permalink.

24 Responses to Naming Conventions for C#

  1. Luis Abreu says:

    why use _? good question. well, if you think about vb (which wasn’t case sensitive the last time i’ve looked), then it may make sense for instance, say you’ve got an IdAccount field. using idAccount for the field and IdAccount for the property won’t work. so, that’s why i use the _ for private fields (and yes, I’ve noticed that you’ve set the guidelines for C#, but to me, it still makes sense to follow this convention for c#). .

    I agree with most of the other things, though i still prefer another convention for control members.

  2. Paulo Morgado says:

    If I were a Visual Basic programmer, I would sufix private fields with Field and private events with Event.

    But this case “sensitiveness” of C# is one of the things I like about it (and, also, one of the things I don’t like about Visual Basic).

  3. luisabreu says:

    Well, i’m not sure if case sensitivity is a good thing. Jeff “horror” Atwood doesn’t really like it and i think i agree with what he says here:

    http://www.codinghorror.com/blog/archives/000860.html

  4. Well, I don’t.

    But I can see you do.

    Just looking at the way we write our names everyone can see the importance each one of us gives to casing.

    From Jeff’s referenced article (http://www.somethinkodd.com/oddthinking/2005/10/27/the-case-for-case-preserving-case-insensitivity/) I only have to say that my name is Paulo Morgado and, unless it’s a misstype, I wouldn’t like to see it written as pAuLo MoRgAdO or some other variation.

    Casing is important and you agree it is. That’s why you use pascal and camel casing in your code instead of underscores separating words, right?

    And why does the Visual Basic IDE keep correcting the casing if it’s case insensitive? Why not uper case or lower case everything?

  5. Miguel says:

    Paulo:

    Without the prefix how can you make a difference between a property and private member:

    public class TestMeClass
    {
      private int test;
      public int Test
      {
        get { return test; }
        set { test = value; }
      }
    }

    The main issue is not for C# but for case insensitive languages such as VB.NET or Delphi.NET ( In this case these languages can interpret the variable either way; also if you are making a class library that library can be used by any .NET client).

    I agree with you idea of prefix, it does make the code stands out.

  6. Miguel:

    I can differentiate them by the casing.

    These are “my” naming conventions for C#.

    I do have a proposal for case insensitive languages: suffix fields with Field.

    Since this convention is for private members only, there’s no problem with consuming this classes using case insensitive languages.

  7. Kenneth Siewers says:

    Well, I actually prefer using the underscore for prefixing my private fields. This is simply because they group together in Intellisense. Whenever I am looking for a private field, I just type in the underscore, and all my private fields show up (including the nasty “_AppDomain” interface Microsoft left behind).

  8. Fluxtah says:

    private int foo;
    public int Foo
    {
      get { return foo; }
      set { Foo = value; }
    }

    Check the code carefully, I’ve seen this happen and a dev take half a day for me to come over and say ‘I see your problem, thats where your stack overflow problem is’

    And he was astonished at my good eyes.

    Granted, this is a head slapping mistake, maybe not enough coffee, but from my point of view having a more user friendly convention can avoid this issue, thats why I like using underscores.

    private int _Foo; is much less prone to this;

  9. It’s not without problems and It has happened to me a few times. Fortunately, this has been the only situation where I’ve got a StackOveflowException and I always know what and where to look.

    But, on the other hand, that revels that that developer was unable to debug and he can do a lot worse and not so obvious mistakes. And no amount of prefixes can help you there.

  10. Betty says:

    So the following parameter for the function FindPerson hides the class member variable? that just seems silly. I like underscore prefixes.

    public class Person {

      private int personId;

      public int PersonId {
        get { return personId; }
        set { personId = value; }
      }

      public void FindPerson(int personId) {
      }

    }

  11. And what does the underscore prefix mean?

  12. Betty says:

    does it need to mean something? I would have thought the whole stopping name clashes was enough to warrant the use of another naming convention in that case. The underscore just happens to be what I use.

  13. I like when things mean something to me. And, since the underscore means nothing to me, it kind of gets in my nerves.
    It’s just the way I am.

  14. Craig says:

    I use the underscore as well, to me it means private withing the scope of the class, so:

    private int _Var;

    public int Var
    {
      get { return _Var;}
     set { _Var = value;}
    }

    and

    private void _PrivateMethod()
    {
    }

    and

    public void PublicMethod()
    {
    }

  15. Wich is as good a convention as:

    private int var;

    public int Var { … }

  16. Dale says:

    I think the use of the underscore should be avoided in naming for all languages, including SQL. In VB, rather than prefixing _ or m_, why not just prefix m or if you like to prefix the type, then do that.

    The underscore is a little finger character on a standard keyboard. That finger does not have the strength of any of the other fingers. Over use of the underscore and other special characters typed by the little fingers of either hand lead to repetitive motion disorders. There just no reason to have to type an underscore over and over and over again.

  17. paulo says:

    I had never thought of that, Dale.

    But my view is: why prefix it at all?

  18. David In So. FL says:

    One of the things I like about VB is the fact its case insensitive. Nothng like spending a couple hours to realize its a single case letter typo.

    I am a “looker” not a character by character “reader” so I miss caps all the time. Lots of people miss seeing individual caps. Its the way the mind works. If you looked into it you would see that the brain is kind enough to change what we see so it looks the way we expect it to. There are a lot of examples of this. This is the reason caps are problematic. Has nothing to do with a person’s skill at debugging.

    The rest will date me. I started with vb 1.0, well actually I started with Basic from the DOS days.

    I like using prefix to denote scope. m or c for class scope (depending on your upbring or shop standards if coming from vb6). They are easier to touch type then the underscore as well. g for global variables.

    In all your examples you can’t tell at a glance what the scope is.

  19. paulo says:

    Hi David,

    I like the case sensitiveness of C#.

    And after a few stack overflow exceptions, you start wondering what’s going on and look for a property reading or writing itself instead of its camel cased backing field. :)

    I’ve grown accustomed to recognize what’s camel cased and what’s pascal cased (and mi sight is not that good). Meaningless prefixes (like _, m_, c_, s_, ?_) are noise to me. And noise bothers me.

  20. Will Vousden says:

    Paulo,

    Your suggestion to use camel casing for private fields is problematic in my opinion, as it introduces the possibility of conflicts between parameters/local variables and fields. This is easily solved for instance members by using `this.` to remove the ambiguity, but what about static fields? I’d rather not have to type out the entire class name every time I want to refer to a static field (and I don’t like the idea of having to change how I access a field in the specific case of a conflict).

    Also, you suggested earlier suffixing a field with `Field` for case-insensitive languages; how is this any different from prefixing them with an underscore or something similar? It’s just as redundant.

    I *want* to do away with all the `m_` prefixes scattered around my code, but can’t think of a robust and consistent way of doing so.

  21. paulo says:

    The only conflict that can’ be resolved is between parameters and local variables.

    Instance fields can be qualified with the this keyword and static (Shared in VB) with the type name, although I would like to see some keyword being used inside the type’s code.

    As for case insensitive languages (like VB), sufixes like Field and BackingStore are only meaningfull if it’s what they are for and tend to go away with auto-implemented properties.

  22. Robert Sewell says:

    Good stuff, except for the private variable underscore thing.

    “The only conflict that can’ be resolved is between parameters and local variables.”

    Which is reason enough for me to use underscore prefixes for private variables. It does have meaning, it means “I’m a private variable not to be confused with the parameter I’m getting/setting” so it’s baffling to me why you insist it’s just noise.

    Also, as Kenneth said, it groups better in Intellisense, and it doesn’t get in the way of reading the variable’s name as do prefixes like ‘m’, ‘g’, and ‘c’ or suffixes like ‘Field’.

    I’ve no problem if you do it your way, unless you come work in my shop. Then you’ll have at least one problem with code reviews. :)

  23. paulo says:

    StyleCop takes care of naming convention reviews for.

    And I’ve worked on projects where the convetion is anything but mine. :)

  24. suresh says:

    it is very usefull

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>