Share via


Field names...

There are three common choices for field name conventions in C# code:

  1. No prefix ("string name;")
  2. Underscore ("string _name;")
  3. MFC-style ("string m_name;")

I label the third MFC-style because that's where I first encountered it.

In the past, I haven't expressed a strong opinion for any of these, and I've written some C# code that used style #1 and some that used style #3. I recent experience, however, has pushed me in one direction.

On Monday, I did two separate code reviews. One was for a C++ class that one of my teammates has written (we do code reviews on all of our code), and the second was on a C# sample written by a C# PM.

When I was reading the C# code, it was hard to follow in places, and it took me a while to realize that what I was missing being able to know instantly whether an identifier was a field, or whether it was a parameter or local.

So put me firmly in the MFC-style camp for naming. #2 is also a reasonable choice, but I think it feels to much like a compiler-defined construct for my taste. Thankfully, I'll have refactoring when I need to revisit my old C# code...

Comments

  • Anonymous
    March 09, 2005
    My choice is #1, but I always reference the variable as "this.variable" in the code. Keeps the variable name "clean" and shows explicitly (via a language construct) the intention.
  • Anonymous
    March 09, 2005
    The comment has been removed
  • Anonymous
    March 09, 2005
    We use prefix 'my' for instance fields and 'our' for static ones. This usually looks find though sometimes resutls in werdly-looking phrases (like 'bool myIsInitialized')
  • Anonymous
    March 09, 2005
    We use prefix 'my' for instance fields and 'our' for static ones. This usually looks fine though sometimes results in weirdly-looking phrases (like 'bool myIsInitialized')
  • Anonymous
    March 09, 2005
    Ditto for me. What you call MFC style is Hungarian notation, which is deprecated these days in favour of the .net framework design guidelines (http://blogs.msdn.com/brada/articles/361363.aspx).
  • Anonymous
    March 09, 2005
    I tend to use method one.
    Except when dealing with underlying property fields, then I use method 2.
    As far as I know that is how it should be done according to the microsoft msdn naming convention.
  • Anonymous
    March 09, 2005
    I personally use a convention I started to use with C++, many years ago, after reading Marshall Cine's C++ FAQ:

    http://www.parashift.com/c++-faq-lite/index.html

    i.e: I write string name_;
  • Anonymous
    March 09, 2005
    Well, I know I'm a lowly VB.net programmer :), so that rules out #1 for me, so I tend to stick to #3. However I also try to use the property for get/set whenever possible on the rationale that I might have validation logic in there and it makes sense to validate inside the class as well as with external data.
  • Anonymous
    March 09, 2005
    I use one, VS does a nice job of giving the definition hints through tooltips to identify if its local variable, field or a parameter and its cleaner to read this notation in calculation intensive code
  • Anonymous
    March 09, 2005
    The comment has been removed
  • Anonymous
    March 09, 2005
    I just can't get into putting "this." in front of member variables in C#. I am not sure when or why I started it, but I always prefix member variables with "" as in #2. It makes it really easy to do code reviews.

    "m
    " would probably be my second choice, but that requires one more unnecessary keystroke in my opinion to add the "m".

    Anything like "mstr" or "mstr_" in front of string member variables, for example, gives me a headache. I actually have to process that prefix, which often distracts me from my goal of reviewing the code. It is a few more keystrokes as well. A lot of people like it and are more comfortable with it, however, so to each his/her own.

    As long as the developer is consistent throughout the code and has some differentiation between member variables and local variables/parameter, I can deal with it. As for myself, I want to keep it very simple and type the least amount as possible.
  • Anonymous
    March 09, 2005
    I find the convention of declaring variables just before you first use them (in a function) to be helpful in determining scope. In combination with keeping functions as short as possible, naming conventions become much less important.

    In VB.NET I will prefix private variables with _, just to distinguish them from public properties. This is not necessary in C#, because of case sensitivity (name != Name).

    So, for C# (1) is best for me, and in VB.NET I use (2). I agree with Code Monkey that the IDE could make this more obvious through color coding.
  • Anonymous
    March 09, 2005
    I'm in Steve McConnell's camp: use some sort of method to distinguish class members from global and local. It's taken me awhile to get used to it, but m_variable (option #3) has grown on me. I agree about option #2 being confusing with compiler directives.

    I also think one shouldn't rely on IDE functionality to make code readble. IDEs change and not everyone uses the same IDE. Some folks even do code reviews via hardcopy. <gasp!>

    Make the code read clearly in all environments, not just one.
  • Anonymous
    March 09, 2005
    "...IDE could make this more obvious through color coding"

    I use Eclipse when I'm doing Java work, which formats the various instance members, class members, etc. differently. To my chagrin I find it difficult to remember what the various formatting means...
  • Anonymous
    March 09, 2005
    we use:
    - no prefix for class fields,
    - (2) for method fields and
    - prefix 'p' for parameters.

    Also, all private class members, including methods, start with lower case.

    Simple and works great during development and for code reviews.
  • Anonymous
    March 09, 2005
    As a side note, style (2) would actually be "illegal" in C++, where identifiers starting with an underscore are reserved (for either the compiler or library)
  • Anonymous
    March 09, 2005
    If you are confused about the scope of a variable, you can take it as a sign that your method is too big, or perhaps the class is.

    If you have to use a local variable with the same name of a class variable, then you may have duplicated code or a class which do too much or do unrelated things.

    The following code:

    Action action = new Action();
    action.Do("one", a, b);
    action.Do("two", a, b);
    action.Do("three", a, b);

    Can be refactored to:

    Action action = new Action(a, b);
    action.Do("one");
    action.Do("two");
    action.Do("three");

    In this case a and b are available to the whole class. The Do-method should not need to declare variables named a or b.
  • Anonymous
    March 09, 2005
    I thought #2 was the recommended MS coding guideline. At least, it's the one we standardized on in ASP.NET.
  • Anonymous
    March 09, 2005
    There's a color coding suggestion in ladybug that you can vote for.

    http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=56d30beb-33a9-45b0-85db-6a31f747de2b

    http://www.torqsoftware.com/blogs/apolon/2005/03/field-name-colors.html
  • Anonymous
    March 09, 2005
  1. Agree with Thomas--if you can't figure out easily whether a variable is local or a member, it's time to refactor (I should know, I have plenty of places where this is true...).
    2. You should be using Source Insight, which has gojillions of features to help with this, including color-coding based on type of variable (member vs. local vs. global vs. ...), a context window that displays the declaration of whatever you have your cursor on, et al. It's all that and a bag of chips! http://www.sourceinsight.com/features.html (No affiliation, other than hoping they continue to do enough business to release new versions :).)
  • Anonymous
    March 09, 2005
    ReSharper already allows you to change the syntax for fields, locals, parameters, events etc. Simple, $99 and you can have it too.

  • Anonymous
    March 09, 2005
    Although C# inherited the C++ syntax, it has some roots in Delphi, too (go Anders!). While the C++ convention is "m_" (as in m_MyField), the Delphi convention is "f" (as in fMyField). I have tried the MS guidelines, but prefer to use "f" (don't knock it till you've tried it! :-). Read about why I like "f" (other than not forgetting those roots) at http://www.robertbullen.com/codeslinger/.

  • Anonymous
    March 09, 2005
    The comment has been removed

  • Anonymous
    March 09, 2005
    c# style use camel casing for all variables, and if you keep your methods short you should be able to easily identify parameters from members by quickly looking at the function signature. I use the rule of thumb that if a function is bigger then one page in your editor it is time to look at making a new class or function. I have no problems having dropped all hungarian notation from good oop code.

  • Anonymous
    March 09, 2005
    I use #2 and a this. prefix to boot. This combo saves a lot of time in Visual Studio because I can type "this._" and get a list of all my class variables.

    As for the possible confusion with compiler directives -- while the C# standard does reserve two initial underscores for use by the compiler, there are currently no such things either present or planned AFAIK. And a single underscore is not reserved anyway.

  • Anonymous
    March 09, 2005
    The comment has been removed

  • Anonymous
    March 09, 2005
    I support prefixing with "this." in constructors. This practice removes silly mistakes like assigning something to itself.

    I find it easier to refactor when I use the same naming conventions all over the place: camelCase for all locals, PascalCase for all publics.

  • Anonymous
    March 09, 2005
    The comment has been removed

  • Anonymous
    March 09, 2005
    I myself use a style that I did not see listed before. I have been using it for years already, so I lost where I picked it up, but my best guess is that it was inspired by Borland's Delphi library code. So feel free to call it 'Delphi style'.

    The style is this: I use a capital 'F', followed by the field's name written with an initial capital, so Eric's original example would be:

    private string FName;

    Note how this style is similar to the more common convention of prefixing interface names with a capital 'I'.

    I have found this style very useful, because it means that any identifier that does not start with a capital is a local variable (or argument), and I know that using or modifying it will have only local effects within the method.

    As a variation on this, I use the prefix 'G' (for 'Global') on any static fields. Once again, this makes it easy to see what the scope of a write to a field is; If I am writing to a field prefixed with a 'G' in code that I wrote some time ago, I know I should be extra careful not to cause undesirable side-effects.


  • Anonymous
    March 09, 2005
    Eric Gunnerson discusses field names in C# code. As mentioned before my preference is his option #2, underscore ("string _name"). One reason is that you don't have to think so much when naming constructor parameters used to initialize member variables:...

  • Anonymous
    March 09, 2005
    I am in camp III, but slowly moving towards camp I with a this. prefix. but lately I came across a case in which I wished I had used m_.

    I made a spelling error, but no compiler and no intellisense complaint, and I just kept wondering why that member variable was not initialing... As a matter of fact, it was with the help of intellisense that I made that error.

    Can you spot it? ;)

    class SomeClass
    {
    public string subscriptionMessage;
    public string unsubscriptionMessage;
    public string errorMessage;

    public SomeClass( string subscriptionMessage, string unsubscriptoinMessage, string errorMessage)
    {
    this.subscriptionMessage = subscriptionMessage;
    this.unsubscriptionMessage = unsubscriptionMessage;
    this.errorMessage = errorMessage;
    }
    }

  • Anonymous
    March 09, 2005
    The comment has been removed

  • Anonymous
    March 10, 2005
    Personally, I like the naming convention advocated by Scott Meyers, and Andrei Alexandrescu:


    string name_;


    It doesn't feel like a compiler generated construct, the naming doesn't interfear with readability or asthetics, and its meaning is pretty clear.

  • Anonymous
    March 10, 2005
    And

    string name_;

    even works in VB6:

    Dim name_ As String

    But that's a pure coinsidence, I guess?

  • Anonymous
    March 13, 2005
    'm' for fields
    'a' for in parameters
    'the' for out paramters
    'aThe' for inout params
    '' for local vars (i.e. no prefix)

  • Anonymous
    March 14, 2005
    I seem to be in the minority, but I can't stand prefixes on variable names. Spare me from ever working with Hungarian-notated code! Put me in camp #1.

    If approach #1 was not an option for some reason, then appending an underscore seems like a reasonable (and less obtrusive) compromise.

  • Anonymous
    March 16, 2005
    Since I hate trying to type lots of _'s (shifted characters are bad m'kay) I prefix member variables with just the 'm':

    mMembershipList;

    otherwise no prefixes allowed.

  • Anonymous
    March 17, 2005
    #3 is too much, #1 is too little, #2 is just right :)

  • Anonymous
    March 21, 2005
    http://dir.zuoce.com/Finance_and_Investment/
    http://dir.zuoce.com/Entertainment/
    http://dir.zuoce.com/Agriculture/
    http://dir.zuoce.com/Electronic_Commerce/
    http://dir.zuoce.com/Computers_and_Internet/
    http://dir.zuoce.com/Toys/
    http://dir.zuoce.com/News_and_Media/
    http://dir.zuoce.com/Telecommunications/
    http://dir.zuoce.com/Arts_and_Crafts/
    http://dir.zuoce.com/Trade/
    http://dir.zuoce.com/Apparel/
    http://dir.zuoce.com/Manufacturing/
    http://dir.zuoce.com/Conventions_and_Conferences/
    http://dir.zuoce.com/Food_and_beverages/
    http://dir.zuoce.com/Jewelry/
    http://dir.zuoce.com/Government_Agents/
    http://dir.zuoce.com/Travel/
    http://dir.zuoce.com/Packaging/
    http://dir.zuoce.com/Corporate_Services/
    http://dir.zuoce.com/Industrial_Supplies/
    http://dir.zuoce.com/Education/
    http://dir.zuoce.com/Transportation/
    http://dir.zuoce.com/Chemicals_and_Allied_Products/
    http://dir.zuoce.com/Employment_and_Work/
    http://dir.zuoce.com/Business_Opportunities/
    http://dir.zuoce.com/Architecture/
    http://dir.zuoce.com/Beauty_and_Fitness/
    http://dir.zuoce.com/Companies/
    http://dir.zuoce.com/Gifts_and_Occasions/

  • Anonymous
    June 07, 2009
    PingBack from http://greenteafatburner.info/story.php?id=4172

  • Anonymous
    June 13, 2009
    PingBack from http://hairgrowthproducts.info/story.php?id=403