29

What is the best practice, most commonly accepted naming conventions for private variables in C#?

  1. private int myInteger;
  2. private int MyInteger;
  3. private int mMyInteger;
  4. private int _myInteger;
  5. private int _MyInteger;
  6. Mysterious other option

Which do you use and why? (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

Tamara Wijsman
  • 8,259
  • 14
  • 58
  • 94
Vaccano
  • 4,028
  • 5
  • 31
  • 37
  • 1
    C# has standards for this, see http://stackoverflow.com/questions/14967/c-coding-standard-best-practices/14974#14974 – Tamara Wijsman Sep 12 '10 at 14:01
  • 8
    It's not nice to talk about private variables in public. Sorry, just had to. – Mark C Oct 19 '10 at 14:30
  • 8
    @Mark I think it should be "private members" for that to be suggestive. – EpsilonVector Nov 01 '10 at 18:04
  • @Epsilon I am hoping I was not indulging in toilet humor but simply joking about private versus public variables. – Mark C Nov 01 '10 at 18:50
  • Definitely go with the Microsoft guidelines, as btlog refers to. Most well-written code uses these guidelines or something close to them. You can use FxCop to help you adhere to the guidelines. – Kyralessa Nov 01 '10 at 23:37
  • you missed two more: m_MyInteger, and m_myInteger – AareP Mar 05 '11 at 18:18
  • @AareP -- those have been deprecated, from what I remember. – Rei Miyasaka Aug 16 '11 at 05:08
  • Why not use Auto-Implemented Properties? http://msdn.microsoft.com/en-us/library/bb384054.aspx – Kyle B. Sep 09 '10 at 18:05
  • I use the same as azheglov (m_someVariable) with the exception of I only use _someVariable within local scope to a method. – lord-fu Nov 01 '10 at 17:33
  • Option 2 could cause collision with encapsulating properties for which pascal case is recommended, besides, private and internal fields should not have prominent features like a leading uppercase character. – toplel32 Dec 04 '14 at 15:39
  • Option 3 looks like it has a big wart, that style is most often used by C++ programmers who must just 'get the job done' and don't have time to predict potential collisions. Besides, early IDE's didn't have features to rename all occurences of a field (like in Visual Studio), and manual replacement is tricky. I would advice against hungarian-like conventions in C# and VB because the prefixes are useful as petty variable names, for example I sometimes use 'm' for a `System.Decimal`. – toplel32 Dec 04 '14 at 15:39
  • Option 4 is widely used/abused and may therefore seem a good candidate, but its not. It is true that a leading underscore avoids naming collision with variables, but a field identifier should be descriptive enough to avoid that anyway. I assume that this convention was invented out of laziness just as with option 3, but ultimately it will cause alot of noise in your code, most prominently in the constructor. My advice for C# on this is; only use underscores in identifiers to suggest an abstract notion, not to prevent collision. Example: `Mscorlib_CollectionDebugView`. – toplel32 Dec 04 '14 at 15:40
  • Option 1 is the best. It is humble, noiseless and forces you to come up with meaningful names. – toplel32 Dec 04 '14 at 15:40

17 Answers17

45

The MSDN class design guidlines http://msdn.microsoft.com/en-us/library/ta31s3bc.aspx recommends option 1 - myInteger.

I have always used this style. I have a personal dislike for the _ character.

btlog
  • 626
  • 5
  • 4
  • 1
    I have disliked the _ character till resharper added mid string matching to intellisence. Now I can type `myInteger` and it will match on `_myInteger`. But I did not know that MSDS says to not use the _ – Vaccano Sep 09 '10 at 18:49
  • @Vaccano I'm pretty sure that _ or m_ prefix are reserved to private variables that are used in properties. – Evan Plaice Sep 12 '10 at 01:21
  • I also do this. People argue adding prefixes for protected variables since they may be used by a language that is case insensitive (like VB) and it's often to have the backing property of `Foo` be `foo`. I say, who cares? If someone's stuck with VB they'll be stuck writing `me.foo`. – Matt Olenik Sep 20 '10 at 21:21
  • 4
    If you use option 1, how can I tell if `myInteger` is a variable local to a method, or a private class member? – Wizard79 Oct 19 '10 at 14:47
  • 4
    @Lorenzo `this.myInteger` ;) – TWith2Sugars Nov 01 '10 at 15:43
  • 12
    But but... "this" is 4 characters and "_" is only one! Actually, that guideline makes a lot of sense but at my office everyone loves underscore and hates seeing "this.Foo", for whatever reason. Sometimes the only guidelines that matter are the ones your workplace forces on you. – CodexArcanum Nov 01 '10 at 16:15
  • 2
    The argument about the number of characters is debatable. You don't have to type `this` every time, only in the methods where a local variable with the same name is present. However, you are required to write an extra symbol every time if you use an underscore. With what I agree is that sticking to your local code style agreement is always important. – Malcolm Feb 01 '12 at 23:30
  • 1
    ^_^ ... how can you dislike that little guy? – Zachary Yates Jan 23 '13 at 20:31
  • 1
    Usage guideline is not naming guideline. There is no naming guideline on MSDN for private field. Underscore is much better than using this. – Pavel Hodek Mar 04 '14 at 23:50
  • I agree with this style as well. Especially if you use Resharper, where you can make fields, properties, local variables, constants, and mutable local variables have different colors, which resolves all reasonable complaints with this style. – Magus May 05 '14 at 14:53
  • See [C# Coding Style](https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md) – Theraot Jun 27 '19 at 19:35
  • There is an updated documentation since, which separated the [General Naming Conventions](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions) from [Field Design](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/field). The naming simply states "DO NOT use underscores, hyphens, or any other nonalphanumeric characters." I do not know how Microsoft usage of `m_` prefixes for private fields comply with this, but I guess they just don't. – Adam L. S. Feb 06 '23 at 13:41
28

I use option #4 above:

private int _myInteger;

I like to have some indication of scope in my variable names, and the underscore is sufficient for that purpose. It's also quite easy to read.

Matt Dillard
  • 389
  • 2
  • 5
  • 5
    I am not agree that it is easy to read, especially if you have to operate with several variables. – Restuta Sep 29 '10 at 16:55
20

I use the following naming scheme:

  • 1st (myInteger) for local scoped variables
  • 2nd (MyInteger) for public properties
  • 4th (_myInteger) for private variables
Zafer
  • 599
  • 2
  • 10
15

I think the option 4 is really the most readable option. It helps you from having to do this:

public Person(string name, int age) 
{
    this.name = name;
    this.age = age;
}

It also makes all private members more noticeable. In the following example, where the heck is age coming from? Without the this qualifier it is harder to tell.

private void Method()
{
    var x = 2;
    var y = age + x;
}

This is way easier to understand:

private void Method()
{
    var x = 2;
    var y = _age + x;
}
ChaosPandion
  • 6,305
  • 2
  • 33
  • 33
  • 2
    I used to swear by your first example, but after trying option #4 for a while I much prefer using underscores as a prefix for private fields. – Jeremy Wiebe Sep 09 '10 at 17:47
  • 2
    I say, use 1 for private variables, use 4 for private variables used in properties. – Evan Plaice Sep 12 '10 at 01:22
  • 2
    I have to disagree with ChaosPandoin. To me, both implementations of Method() are easy to read. As soon as I see the age variable (or _age) and notice that it's not declared in the method, I realize it must be declared elsewhere in the class. The this qualifier is awful but at least it's confined to the constructor method. – Big McLargeHuge Dec 18 '12 at 00:33
11

First off, PascalCasing is commonly reserved for public properties, consts, methods, etc of the class. So I would skip 2 and 5.

Second, hungarian notation is discouraged in the .NET world, so (uh, I think) 3 is right out. Assuming that's what is going on with 3.

That leaves with camelCasing and _camelCasing. I typically use _camelCasing for class variables, and plain old camelCasing for variables scoped to a method or narrower. Camel casing is the accepted standard used for method arguments, protected/private variable names and variables within a method or narrower scope.

I also like to prepend with the underscore so that my private variables are grouped in my intellisense. However, I only do this for variables scoped to a type. Variables declared within a method or narrower scope I leave the underscore off. Makes it easy to keep them separate and keep less used variables together.

Ripped Off
  • 3,757
  • 3
  • 21
  • 24
  • 2
    I don't understand why you would use _camelCasing for class variables, since its usually obvious that they are class variables. – alternative Sep 09 '10 at 20:11
  • 1
    @math no, its not obvious in the intellisense. Remember, fields (class-scoped variables) have (almost) the same icon as method scoped variables, so they look exactly the same if you don't look closely. The underscore helps differentiate them visually and keeps them grouped together, which helps if you aren't using them often (which you shouldn't be as state is the enemy of bug free programming). – Ripped Off Sep 09 '10 at 20:24
  • I never said anything about the Intellisense. I'm talking about the difference between Color.ClassMethod() and myColor.InstanceMethod(), namely that it should be obvious that since Color is a class, ClassMethod() is a class method. – alternative Sep 09 '10 at 22:25
  • @math you before: `I don't understand why you would use _camelCasing for class variables` you after: `I'm talking about the difference between Color.ClassMethod() and myColor.InstanceMethod()` Excuse me while I'm confused. Listen, I use class variables rarely, so its nice to be reminded of their names by hitting _ and having them all pop up in the intellisense nice and grouped. – Ripped Off Sep 13 '10 at 11:46
  • 2
    @mathepic: When Will says "class variables" he means (private) instance fields. You seem to have interpreted what he said to mean static members; but that's not what he said. – Dan Tao Sep 20 '10 at 15:14
  • If [this is the specification for Hungarian Notation](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa260976(v=vs.60)?redirectedfrom=MSDN) then it is not inherently prohibiting `mMyInteger`. – Adam L. S. Feb 06 '23 at 13:34
4

private int integer

If you get confused between member and local variables in a method scope then you probably need to refactor.

Ryan Roberts
  • 491
  • 2
  • 7
  • +1: that's what I believe is the point. BTW: I see its source, but the name `integer` could be better reworded, maybe `value` ? – Wolf Nov 18 '14 at 14:27
2

I wouldn't call it "my" anything!

But I'd say

class C
{
     int VariableName { get; set; }
}

quite often this is nicer than having explicit variables. If I had an explicit private variable i'd call it int _variableName;

CJBrew
  • 121
  • 2
2

I do option #4 because that's what the SSCLI looks like, but honestly I don't care that much on naming of private variable. Public is a different story.

BTW you forgot m_MyInteger

Conrad Frix
  • 4,155
  • 2
  • 18
  • 34
1

In C++ I tend to use _ as I switch editors a lot which doesn't allow me to see if it's private.

For C# I tend to to leave the _ away as Visual Studio allows me to see if it's private.

I tend to use the Camel Case way to do this.

Tamara Wijsman
  • 8,259
  • 14
  • 58
  • 94
1

I use 4 (private int _myInteger;) because:

private int myInteger;

This is how I name my local variables.

private int MyInteger;

This is how I name constants.

private int mMyInteger;

This is not C# style.

private int _MyInteger;

This looks strange.

Victor Hurdugaci
  • 3,243
  • 18
  • 20
1

I believe the best way to do it (in C#/.net anyway) is a combination of 2 and 6:

private int MyInteger { get; set; }

There's theoretically no variable at all here, but it looks and acts like a private instance variable. If we need to add some business logic to that value (it's a completely internal value, so we can do anything we want to it after all) then it's already 'propertyized' for us. A hot steaming cup of win!

Task
  • 437
  • 3
  • 7
1

with the underscore.

Bill Wagner explains why in Effective C#. But I would never name an integer myInteger, better something like _age or _length. Including the TypeName in the instance name is a horrible practice. Names should be self explanatory and since C# is Type-Safe types can be found out att all times.

Caspar Kleijne
  • 201
  • 3
  • 11
1

You need to give a more specific example, but:

private int count, private int badFileCount, private static readonly int ReconnectAttemptsLimit

By the way, you get all this FREE when you install and start using the latest and greatest MSFT Stylecop.

Job
  • 6,459
  • 3
  • 32
  • 54
0

I go by option 5: private int _MyFoo

I don't see any real competitive advantage over _myFoo though.

mafu
  • 313
  • 2
  • 12
0

Juval Lowy's IDesign C# Coding Standard is quite popular. This standard recommends prefixing private member variables with "m_" (Option 6). That's what we do in our team.

private int m_myInteger;

Option 4 (_myInteger) is an acceptable variation of this standard.

I didn't like the MSDN recommendation (myInteger), because it makes it difficult to tell a private member from a local variable. Their recommendation, of course, solves this problem by qualifying private members with this, which seems redundant to me.

azheglov
  • 7,177
  • 1
  • 27
  • 49
0

Use camelCasing for private variables like myInteger

Consider a preceding _ if the variable is a backup for a property to reduce confusions-
Variable _myProperty for property MyProperty

Gulshan
  • 9,402
  • 10
  • 58
  • 89
0

I have ReSharper name my variables, not only mine but everyone else does this as well. There is a great amount of consistency trough the project.

Sevki
  • 101
  • 5