54

I am going to be working on a bit of C# code on my own but I want to make sure that I follow the most widely accepted naming conventions in case I want to bring on other developers, release my code, or sell my code. Right now I am following the naming convention that Microsoft has set as they seem to be the most widely accepted. The one thing they don't mention though is naming for private fields. For the most part I have seen them named in camelCase like protected fields however that present me with an issue as parameter names should be in camelCase. Take the following constructor for example:

public GameItem(string baseName, string prefixName, string suffixName)
{
    //initialize code
}

Now if I use camelCase for the private fields too there is a naming conflict unless I use "this" in order to access the class fields (which I think is against most standards not to mention means more typing). One solution is to give the parameter a different name but that does not make logical sense to give the same data 2 different names. The only other solution that I know of that was common in C++ coding is giving private members an underscore at the beginning (_camelCase). Is that solution commonly accepted with C# coding? Is there another solution to this problem (like only using properties (which use PascalCase) to access fields, even in the class itself)?

V0d01ey
  • 47
  • 1
  • 6
ryanzec
  • 27,284
  • 38
  • 112
  • 169
  • 2
    http://msdn.microsoft.com/en-us/library/xzf533w0.aspx http://msdn.microsoft.com/en-us/library/ms229045.aspx – Jaroslav Jandek Jul 06 '10 at 14:03
  • 9
    Choose one and be consistent! That's what matters... – João Angelo Jul 06 '10 at 14:04
  • 4
    I use "this" for private fields. – gooch Jul 06 '10 at 14:05
  • I use either `this` or public properties with `protected set` and those have first letter capital. Check out M$ **FxCop** if you can. – Jaroslav Jandek Jul 06 '10 at 14:16
  • 1
    Starting to think about it more and it might make more sense to just access them through properties all the times. Two reasons I am think this is that 1. Consistency throughout all the code on how to access fields and 2. If need to add validation checking, I would have to switch all my code to use properties anyways so might as well do it beforehand. What do you think using properties all the time? – ryanzec Jul 06 '10 at 18:24
  • Well, I do not use them *all* the time but a lot - always for public access, mostly for protected, usually not for private. You can easily refactor your private fields. You can't just refactor a public field to public property, because when an assembly links to the field, it will look for field instead of a property. And you can't easily change behavior on field access. – Jaroslav Jandek Jul 07 '10 at 08:08

17 Answers17

62

_camelCase for fields is common from what I've seen (it's what we use at our place and Microsoft prefer for the .NET Runtime).

My personal justification for using this standard is that is is easier to type _ to identify a private field than this.

For example:

void Foo(String a, String b)
{
    _a = a;
    _b = b;
}

Versus

void Foo(String a, String b)
{
    this.a = a;
    this.b = b;
}

I find the first much easier to type and it prevents me from ever accidentally assigning to the parameter called a instead of this.a. This is reinforced by a Code Analysis Maintainability Rule that states:

  • CA1500 Variable names should not match field names.

My other reason, is that this. is optional (Visual Studio / Code prompts you to remove them) if it doesn't collide with a local variable or parameter name, making knowing which variable you are using harder. If you have an _ at the start of all private fields, then you always know which is a field and which is has local scope.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
  • 9
    _camelCase for private fields is not suggested by Microsoft (http://msdn.microsoft.com/en-us/library/ta31s3bc(v=VS.71).aspx). In case of naming conflicts between class and method scope, you can use the this keyword to refer to the class member. This is also what Resharper suggests by default... – Koen Jul 06 '10 at 14:52
  • 1
    I agree with the use of the _camelCase for module level variables or property variables. But as João Angelo said already the most important thing is to be consistent. It's not about what the standards are it's that you have them and enforce them. Koen - Resharper (certainly in v5) uses _camelCase. – Darren Lewis Jul 06 '10 at 18:50
  • 12
    _We _don't _need _your _underscores _here – Callum Rogers Jul 07 '10 at 09:55
  • 4
    If you enable .NET Framework source stepping, or if you use a CLI decompiler tool (such as Reflector or ILSpy) to look at the framework sources, you will notice that even Microsoft has started following this guideline from .NET 3.0+. – Paolo Moretti Jul 24 '12 at 13:10
  • @PaoloMoretti just out of interest, do you have an example class? – DaveShaw Jul 24 '12 at 13:31
  • 1
    @DaveShaw Any class defined in the new assemblies. For example `System.Windows.DependencyProperty` (on `WindowsBase`) has several private fields in `_camelCase`. – Paolo Moretti Jul 24 '12 at 14:16
  • Basically the entirety of WPF seems to be using `_camelCase` for private fields. – Florian S. Nov 22 '15 at 13:52
  • If you check the source code of `.Net Core`, you will find a lot of places where they use `_xyz` convention. – Mohammed Noureldin Oct 30 '17 at 00:13
50

Follow the Microsoft Naming Guidelines. The guidelines for field usage indicate that it should be camelCase and not be prefixed. Note that the general rule is no prefix; the specific rule is not to prefix to distinguish between static and non-static fields.

Do not apply a prefix to field names or static field names. Specifically, do not apply a prefix to a field name to distinguish between static and nonstatic fields. For example, applying a g_ or s_ prefix is incorrect.

and (from General Naming Conventions)

Do not use underscores, hyphens, or any other nonalphanumeric characters.

EDIT: I will note that the docs are not specific with regard to private fields but indicate that protected fields should be camelCase only. I suppose you could infer from this that any convention for private fields is acceptable. Certainly public static fields differ from protected (they are capitalized). My personal opinion is that protected/private are not sufficiently different in scope to warrant a difference in naming convention, especially as all you seem to want to do is differentiate them from parameters. That is, if you follow the guidelines for protected fields, you'd have to treat them differently in this respect than private fields in order to distinguish them from parameters. I use this when referring to class members within the class to make the distinction clear.

EDIT 2

I've adopted the convention used at my current job, which is to prefix private instance variables with an underscore and generally only expose protected instance variables as properties using PascalCase (typically autoproperties). It wasn't my personal preference but it's one that I've become comfortable with and probably will follow until something better comes along.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 8
    The naming guidelines are only concerned about identifiers visible to the outside. – Martin Liversage Jul 06 '10 at 14:12
  • OK what is more correct: this.employee this._employee or this.m_employee? – hellboy Oct 01 '13 at 15:51
  • 1
    @hellboy see my update I now use an underscore prefix and don't typically use `this.` anymore – tvanfosson Oct 01 '13 at 16:33
  • 2
    > Internal and private fields are not covered by guidelines – Maksim Vi. Aug 10 '17 at 19:19
  • The new naming guideline _does_ suggest using prefixes. The suggested answer needs to be updated. [learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions#naming-conventions) `Use camel casing ("camelCasing") when naming private or internal fields, and prefix them with _.` `When working with static fields that are private or internal, use the s_ prefix and for thread static use t_.` – Mikhail Akulov Oct 13 '22 at 08:18
24

Generally there are two widely used ways to name fields (always using camelCase):

Using an underscore prefix

void F(String someValue) {
  _someValue = someValue;
}

Using this. to access the field and avoid name conflicts

void F(String someValue) {
  this.someValue = someValue;
}

Personally I prefer the later, but I will use whatever convention is set forth by the organization I work for.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
19

Short answer: use _privateField, i.e. use leading underscore for private fields.

Long answer: here goes...

Long long ago, Microsoft used to suggest using camelCase for fields. See here. Note when that document was created, 10/22/2008. Pretty ancient.

Recent code base of Microsoft however depicts a different picture.

  1. Take a look at the C# Coding style of .NET Runtime GitHub repository. #3 is the point under discussion. Here is the relevant part

    We use _camelCase for internal and private fields and use readonly where possible.

  2. Also take a look at Coding style of Roslyn repository that specifically says that it follows the conventions of .NET Runtime.
  3. Take yet another look at the .NET Standard contributing page, which also says (at least for now) to follow the same guide as .NET CoreFX, which was a precursor to .NET Runtime.
  4. Prior to consolidation, CoreCLR also suggested following the same guide as CoreFX.
  5. Even WinForms repo speaks of using this same standard.
  6. I think I have said enough. So, to conclude, if you want to follow the guide that Microsoft suggests, I think you know what to do; use leading underscore for private fields like this: _privateField.

My opinion: I too personally prefer leading underscore for my private fields - makes it very easily distinguishable, without needing the this.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
  • 1
    I get what you are saying.. but why then does Visual Studio `CTRL` + `.` autocomplete feature on a constructor variable do `this.private = private;` ? Then in the rest of the class its pretty obvious that when I do `neo4jRepository` is `neo4jRepository` - So how does `_neo4jRepository` make is any more clear. I do not understand how it makes it easier distinguishable. I get if you use maybe non DI things like count for one thing and a method with count for another thing.. yea `_count` then means this count. But why on earth is everybody doing this with DI. My eyes are bleeding – Piotr Kula Apr 15 '19 at 14:59
  • This is a matter of convention, nothing more. When you follow a convention, it is easier to understand the code's intention without difficulty - it could be any convention, as long as you are consistent with it. Since more and more people are already _consistently_ using this convention, you better get used to it, otherwise you're eyes only will hurt even more ;-) – Sнаđошƒаӽ Apr 15 '19 at 17:02
  • 1
    Yea, good convention, especially C# 8 underscore `_` is going to be used for a throw away variables.. good luck with not getting confused with that (start using `__` ? *sigh* ). This overuse of underscore to avoid typing `this.` in the constructor (even though VS auto generates this code for you in 2 keyboard taps) actually results in an exponential amount of more typing since the in the entire class you have to type `_` unnecessarily. I get using `_` when you have method hiding class variables. A legitimate reason for framework designers.. not S.O.L.I.D software devs. Just my opinion. – Piotr Kula Apr 16 '19 at 10:04
  • 1
    I don't see how you relate _throw away_ variable, `_` as you call it, with fields beginning with `_`. The former is just an underscore, used in specific context, while the latter has some more characters following it. And BTW, `_` as variable name is not a C#8 thing, it [dates back even earlier](https://stackoverflow.com/questions/6308078/c-sharp-variable-name-underscore-only). – Sнаđошƒаӽ Apr 16 '19 at 12:54
  • 1
    Even more reasons to avoid `_` – Piotr Kula Apr 16 '19 at 13:09
12

In our shop, we started our first C# project using Microsoft's suggested guideline for private members, i.e.

camelCaseFieldName

But we soon ran into confusion between private members and parameters, and switched to

_camelCaseFieldName

which has worked much better for us.

A private member usually has a state that persists outside of a method call - the leading underscore tends to remind you of that.

Also note that using AutoVariable syntax for properties can minimize the need for private backing fields, i.e.

public int PascalCaseFieldName { get; set;}

For a nice concise set of standards that (mostly) follow the MS guidelines, check out net-naming-conventions-and-programming-standards---best-practices

Tom Bushell
  • 5,865
  • 4
  • 45
  • 60
  • 2
    Note that auto properties still use a private backing field, you just delegated its creation to the compiler rather than declaring it by yourself. The funny thing is - the generated name for the backing field is pretty weird. For example: The auto generated backing field for the property `Int32 Count { get; set; }` will be named `k__BackingField`. That's far from any naming guidline, it's even using characters that are invalid for identifiers in C# (but that's okay because you normally never see this unless you use reflection). – Florian S. Nov 22 '15 at 13:57
  • 2
    @FlorianS.: and that's also the reason for this weird name, they don't want to introduce naming conflicts with auto generated and invisible variables. – Tim Schmelter May 25 '16 at 10:44
7

As it was mentioned, Microsoft Naming Guidelines dose not cover private fields and local variable naming. And you don't find consistency within Microsoft itself. If you generate class or Disposable pattern in Visual Studio it will create something like

public MyClass(int value)
{
    this.value = value;
}

or

private bool disposedValue = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
    if (!disposedValue)
    {
        ...
    }
}

Fortunately more and more code was opened by Microsoft, so let's take a look a their repos, e.g. ASP.NET Core MVC

private readonly IControllerActivator _controllerActivator;
private readonly IControllerPropertyActivator[] _propertyActivators;

Or .NET Core

private T[] _array;

You may say, that it's not actually Microsoft, but .NET Foundation. Fair enough, let's take a look at Microsoft repos:

private readonly MetricSeries zeroDimSeries;

But here is ancient Microsoft implementation of MVC

private IActionInvoker _actionInvoker;

So there is not any common practice or official guideline regarding private fields naming. Just choose one you prefer and stick to it.

Kosta_Arnorsky
  • 363
  • 3
  • 7
3

The most important thing is to pick one standard and stick with it. Check out iDesign's C# Coding Standard at IDesign (it's a link on the right side). It's a great document that covers things like naming guidelines. They recommend using camel case for both local variables and method arguments.

TLiebe
  • 7,913
  • 1
  • 23
  • 28
  • 1
    Our .NET dev teams the IDesign coding standards as well. Juwal can't be wrong, right? :) – Riaan Jul 06 '10 at 14:55
3

We use StyleCop to force consistency throughout our code. StyleCop is used within Microsoft enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code.

You can run StyleCop at build time and have it generate warnings for style violations.

To answer your specific question, private fields should be in camelCase and prefixed with "this".

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
John Myczek
  • 12,076
  • 4
  • 31
  • 44
2

Philips Healtcare C# Coding Standard

MSDN - Eric Gunnerson

Edit: I use "this" keyword to access non-static members in C# and Java.

Deniz Acay
  • 1,609
  • 1
  • 13
  • 24
1

Following Microsoft's naming conventions, private fields should be prefixed with an underscore.

For example:

private int _myValue;

Good luck!

Ian P
  • 12,840
  • 6
  • 48
  • 70
  • Identifiers should not contain underscores (it's one of the warnings from **FxCop**). – Jaroslav Jandek Jul 06 '10 at 14:12
  • 1
    It's recommended by Microsoft in their best practice guide. – Ian P Jul 06 '10 at 14:14
  • FxCop will not flag a private field starting with an underscore. – Martin Liversage Jul 06 '10 at 14:15
  • Besides, isn't that for some COM compatibility issue? I see it sometimes in the build reports, but just ignore it. I believe FxCop throws up on linq to sql auto generated classes with _ in public properties. – Ian P Jul 06 '10 at 14:15
  • 2
    FxCop doesn't care about internal identifiers but what's good for external usage should be good for internal one. Also, the underscores look ugly (IMHO). Underscore prefix did not work for some languages that were to be integrated into framework and for interop. Also having a class with 15 private fields named _whatever slows intellisense-typing down. – Jaroslav Jandek Jul 06 '10 at 14:24
  • Also I think I read like 6 years ago in naming conventions that an underscore characters should not be used as a prefix but couldn't find it now on msdn. In any case, M$ programmers use underscores all the time ;). Also, **Ian**, can you link the best practices guide? – Jaroslav Jandek Jul 06 '10 at 14:34
  • 2
    @Ian P: I do not see the recommendation to use underscore prefixes anywhere. Convention only mentions underscores to not use them in classes and such. – Jaroslav Jandek Jul 07 '10 at 07:55
  • 2
    I have found the practice not to use prefixes: `Do not apply a prefix to field names or static field names. Specifically, do not apply a prefix to a field name to distinguish between static and nonstatic fields. For example, applying a g_ or s_ prefix is incorrect.` They do not mention non-public fields specifically, but you get the point. link: http://msdn.microsoft.com/en-us/library/ta31s3bc.aspx – Jaroslav Jandek Jul 07 '10 at 08:01
  • 1
    To me, that reads that it is regarding hungarian notation which is not what I'm speaking about. If you read any of the microsoft employee's blogs, they all (well, all of the ones I've seen) prefix private fields with _. – Ian P Jul 07 '10 at 12:40
  • https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions > To differentiate words in an identifier, capitalize the first letter of each word in the identifier. Do not use underscores to differentiate words, or for that matter, anywhere in identifiers. – tsul Apr 07 '21 at 12:52
1

The convention I use to distinguish between private class variables and method parameters is:

private string baseName;
private string prefixName;
private string suffixName;

public GameItem(string baseName, string prefixName, string suffixName)
{
    this.baseName = baseName;
    this.prefixName = prefixName;
    this.suffixName = suffixName;
}
Dougc
  • 843
  • 11
  • 20
1

I too had doubts about this and then I decided check github codes of Microsoft. Almost every source code I've looked at had underscore usage for private fields.

https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/ document does not seem to mention about this usage.

Mert Sevinc
  • 929
  • 1
  • 8
  • 25
0

Have a look at ReSharper. It will underline all the places where your names do not confirm to ordinary guidelines, and you can customize it. Plus, of course there's loads and loads of other productivity enhancements.

Carlos
  • 5,991
  • 6
  • 43
  • 82
0

I've done much more with VB than C#, so I guess I carry over some practices (prejudices?) from the former to the latter.

I like the private fields of properties to have a leading underscore - especially in C# due to the case-sensitivity (whose idea was that anyway?) And I prefix module-/class-wide variables with "m" as well to reinforce their scope.

If you don't like that, you're really not gonna like this: I generally use type prefixes as well (except for property fields) - "o" for Object, "s" for String, "i" for Integer, etc.

I can't really defend this with a peer-reviewed paper or anything but it works for us and means we're not tripped up by casing or field/parameter confusion.

So ...

Class MyClass

    Private msClassVariable  As String = ""

    Private _classProperty As Integer = 0
    Property Readonly ClassProperty() As Integer
        Get
            Return _classProperty
        End Get
    End Property

    Sub New()

        Dim bLocalVariable As Boolean = False
        if _classProperty < 0 Then _classProperty = 0
        msClassVariable  = _classProperty.ToString()
        bLocalVariable = _classProperty > 0
    End Sub

End Class
SteveCinq
  • 1,920
  • 1
  • 17
  • 22
0

Personally, I hack the parameter names by the prefix "the" such as theSamplingRate. For me, it makes perfect sense :)

Avi
  • 15,696
  • 9
  • 39
  • 54
0

I do this; it's pretty much in line with MSDN.

class MyClass : MyBaseClass, IMyInterface
{
    public event EventHandler MyEvent;
    int m_MyField = 1;
    int MyProperty {
        get {
            return m_MyField;
        }
        set {
            m_MyField = value;
        }
    }

    void MyMethod(int myParameter) {
        int _MyLocalVaraible = myParameter;
        MyProperty = _MyLocalVaraible;
        MyEvent(this, EventArgs.Empty);
    }
}

Here's a little more detail: http://jerrytech.blogspot.com/2009/09/simple-c-naming-convention.html

Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233
  • 1
    I think this was in the guidelines ages ago... at the moment, it definitely is not! I also dislike the implicit access modifiers. – Jowen Jul 15 '13 at 14:41
  • Yeah, it's true. Most coders skip `_`, `m_`, and `s_` prefixes. Anymore, nobody can't tell the scope of a var by its name. Fact is, most coders have reduced their naming to thisName and ThisName and nothing else. To me, it's not right. But I accept it's most common. – Jerry Nixon Jul 19 '13 at 17:56
  • Besides being an outdated convention, it is as ugly as it can get, IMO. – Sнаđошƒаӽ Apr 22 '19 at 15:33
-5
private string baseName; 
private string prefixName; 
private string suffixName; 

public GameItem(string _baseName, string _prefixName, string _suffixName) 
{ 
    this.baseName = _baseName; 
    this.prefixName = _prefixName; 
    this.suffixName = _suffixName; 
} 
Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
ma7moud
  • 423
  • 1
  • 4
  • 8
  • 6
    -1. This convention is not posted as best practice anywhere I've seen, and the post is very poorly formatted. On a more personal level, I think the _'s in the method signature significantly clutters the code, and since it is used there and not in the private accessors, it will be visible all over the client classes too, and not just in your code. – Tomas Aschan Jul 06 '10 at 14:26
  • In addition to adding visual complexity to the parameter names, "_" is often used to denote "private" in other programming contexts. Parameter names are part of the public method signature and, thus, should not use an underscore prefix. Also, little differentiates a method parameter from a local variable, so using an underscore for one and no underscore for the other (or, worse, also for local variables) is inconsistent. – Matt Stoker Dec 19 '13 at 22:46
  • Where did you get this mentioned as _naming guideline_ for C#? The question asks for _guidelines_, not whatever you may be using. And as @Matt described, yours is no standard, and not sensible in any way whatsoever. – Sнаđошƒаӽ Jan 29 '19 at 01:32