44

I have recently started using ReSharper which is a fantastic tool.
Today I came across a naming rule for static fields, namely prefixing with an underscore, i.e.

private static string _myString;
  1. Is this really the standard way to name static variables?
    If so, is it just personal preference and style, or does it have some sort of lower level impact? E.g. Compilation JIT etc?
  2. Where does this style originate from?
    I have always associated it with C++, is that correct?
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Matt
  • 2,730
  • 4
  • 28
  • 35

10 Answers10

32

The Microsoft guidelines are silent about private fields, they are only concerned with publicly visible members.

Common conventions are camelCase, _camelCase and even sometimes the hangover from C++/MFC m_camelCase.

If you use camelCase without a prefix, your property backing fields will differ from the property name only in case, which is not a problem in C#, but won't work in a case-insensitive language like VB.NET.

So many people, including myself, like to use an underscore prefix so that the same standards can be used in all languages. In my experience, underscore is much more common than m_.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • 2
    Why do you think the Microsoft guidelines are only concerned with publicly visible members? http://msdn.microsoft.com/en-us/library/d53b55ey%28v=VS.71%29.aspx – dcp Jun 18 '10 at 16:31
  • 1
    @dcp I agree that the latest MSDN version you link isn't very explicit, but earlier versions were. For example VS2008 help says "The capitalization conventions described in this topic make it easy for developers to understand and work with a library." (which seems to exclude private members), and "Names cannot differ by case alone." (which is patently not true for private C# members). – Joe Jun 18 '10 at 16:37
  • Actually, my point was that MSDN *does* actually give us a guideline on how to name static variables, and the guideline is to use PascalCase. Of course, as somebody else pointed out (and as I alluded to in my answer) StyleCop expects them to begin with a lowercase letter. :) Don't you just love consistency :)? – dcp Jun 18 '10 at 16:44
  • 7
    @dcp - but if the MSDN guideline is only intended to apply to publicly-visible members there is no inconsistency, just ambiguity in the MSDN docs. – Joe Jun 18 '10 at 16:51
  • In more recent guidance, Microsoft are more strongly recommending the use of underscore preceding private variable names to avoid breaking changes with the introduction of new keywords into the language, which we have been seeing more of lately. – Haighstrom Oct 18 '22 at 10:00
31

According to MSDN, use Pascal Case for static fields. I always chuckle when MSDN and StyleCop contradict each other :).

So if you are following MSDN standards, the correct way is:

private static string MyString;
dcp
  • 54,410
  • 22
  • 144
  • 164
  • In that case, what should a public static property be named that returns the value of `MyString`? – O. R. Mapper Aug 10 '18 at 06:24
  • @O. R. Mapper - According to the link in my answer, properties and static fields both use Pascal case. So I would follow that convention. – dcp Aug 10 '18 at 11:26
  • 1
    Your comment skillfully avoids pointing out that that implies the property would have to have exactly the same name as the field, which is, of course, impossible ;) – O. R. Mapper Aug 10 '18 at 11:31
  • @O. R. Mapper - Yes, good point :). In that case, you would probably want to use a different name for the static field vs the static property to avoid the naming conflict. – dcp Aug 10 '18 at 15:06
19

According to StyleCop (and with the default settings), the correct way to name most fields (as specified below) is with a lowercase letter at the start.

SA1306: FieldNamesMustBeginWithLowerCaseLetter

... Field and variable names must begin with a lower-case letter, unless the field is public or internal, const, or non-private and readonly. In these cases, the field should begin with an upper-case letter.

See also SA1309: FieldNamesMustNotBeginWithUnderscore.

Community
  • 1
  • 1
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
11

It's actually the style for a private field, static or not. (At least in ReSharper)

Aren
  • 54,668
  • 9
  • 68
  • 101
  • Yes, specifically private. If you have the underscore on a protected or public field, it will not be CLS compliant. http://msdn.microsoft.com/en-us/library/k5645wwb(VS.80).aspx – Matt Greer Jun 18 '10 at 16:33
  • 2
    ReSharper comes with some *default* style rules (based on conventions the folks at JetBrains decided make good defaults) that can changed. – user2864740 Mar 02 '17 at 06:32
10

UPDATE FOR 2021

Per C# Coding Conventions published 2021 from Microsoft, private static variable should start with s_ prefix followed by camel case. So, it should look like below:

private static string s_myString;
Joon Hong
  • 1,337
  • 15
  • 23
6

The convention is whatever your company's coding standards says it is.

g t
  • 7,287
  • 7
  • 50
  • 85
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
4

The problem I have with the MSDN guideline (use Pascal case) is that it results in there being no distinction between a private static variable and a public (non-static) property. The same issue would arise for static properties - no distinction between static and non-static.

Perhaps this is deliberate?

One way out of this would be to use the same standard for statics as for non-statics but to always qualify use of statics by prefixing with the class name. It may be a few extra characters to type, but it makes the code more readable. For example:

public class Employee
{
    private static Int32 thresholdPercentage = 5;
    public static String TooMuchMessage = "Unacceptable pay rise - sorry!";

    private Decimal _salary = 0.0m;

    public void RaiseSalary(Int32 raiseAmountPercentage)  
    {
        if (raiseAmountPercentage > Employee.thresholdPercentage)
            throw new ApplicationException(Employee.TooMuchMessage);

        _salary *= 1 + (raiseAmountPercentage / 100);

        return;
    }
}
2

For static fields, I've settled on StaticPascalCase (eg. StaticPersonCache) as it clearly sets it apart from an instance variable. This includes private static fields as well as static fields with other visibility modifiers.

For static variables it's less of a concern to me to indicate the public/private visibility through the name than it is to indicate how the variable operates among instances. Also, since there are not (and really should not be) many Static variables the 'Hugarian-like' modifier is not applied often.

Similarly, for thread-static variables ([ThreadStatic] or ThreadLocal) the convention I use is TS_UpperCamelCase (eg. TS_Random). Once again, this "break" from norms conveys very important information that other developers might fail to see on first glance. The name is thus used as a cautionary flag, of sorts.

I use ReSharper and have adjusted the warnings/hints accordingly; most other naming conventions are left at the ReSharper default settings.

My selection of such "non standard" conventions for static/thread-static fields (note: Microsoft uses TS_ in some code in the .NET library) is because I've run into more than one 'quirk' due to misidentification of Static/ThreadStatic/Instance variables: that's much harder to do with StaticX, TS_X, and _x.

user2864740
  • 60,010
  • 15
  • 145
  • 220
0
  1. There is no definitive standard rule for variable names. There are C# compiler requirements for what's allowed and what's not (e.g. can't start with a number), but programming language style rules are generally left up to the programmers / organizations. ReSharper has pre-defined style rules; however, they are merely set up as defaults in a convention over configuration approach and are modifiable.

  2. You can take a look at this Wikipedia article to see the history behind Camel Casing.

Pang
  • 9,564
  • 146
  • 81
  • 122
JD Courtoy
  • 2,855
  • 25
  • 27
0

Other answers here are a bit confusing.

From .NET standard:

DO use PascalCasing in field names.
The field-naming guidelines apply to static public and protected fields.

So example will be: MyStaticVariable, ActiveUserCount, etc.

Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140