11.13
I’m getting sick of the argument:
"Should private fields in a class be prefixed with an ‘_’?"
So I’m going to try and crack this nut once and for all!
Example:
private double _price; //Using “_” public double Price { get { return _price; } private set { _price = value; } }
private double price; //Not using “_” public double Price { get { return price; } private set { price = value; } }
Note: I am well aware I could use an automatic property here, but so not the point =].
So what do Microsoft say? Well here is their Naming Convention section of MSDN. They don’t want to touch this topic it seems as there is no guidance on how to name a private field. When they discuss property naming conventions here this is all we get:
public int Color { get {// Insert code here.} set {// Insert code here.} }
Hmm that was helpful =/.
I got my hands on the iDesign C# coding conventions which you can download from here.
They go down the road of prefixing private fields with “m_” D= ! That is a barrel of worms right there so I’m going to leave it at that!
Arguments AGAINST prefixing with an underscore:
- In intellisense the property of said name and its backing field will appear together.
- C# is case sensitive therefore there seems to be no need for an ‘_’.
- If you wish to differentiate between fields from your local variables / parameters use the “this” keyword to indicate a field from a local variable like so:
public void WithDiscount(int price) { this.price = price; }
- “StyleCop will call you a son of a whore if you use underscores” @blowdart
If you can think of anymore please leave a comment.
Arguments FOR prefixing private fields with an underscore:
- When I got my C# Certification I was taught to use an "_".
- You do not need to put “this” in your code before private fields.
- If you don’t wish to use “this” everywhere you have to get creative with naming.
- You don’t need to think about what a variable is, “_” prefix makes it quite clear.
- All private fields with be grouped together in intellisense:
- “..it allows for the same naming convention to span C# and VB.NET” @csharphacker
- R# by default says so!
- I said so >.<!
Again If you can think of anymore please leave a comment.
Conclusion
What sells the “_” for me is the fact I don’t have to put this everywhere in my code when working with private variables nor do I have to think about alternate naming for local variables or parameters to avoid using this.
What is you opinion? Let the battle rage on..!


Holsee’s Blog » C# private fields to ‘_’ or not to ‘_’ that is the Question…
Thank you for submitting this cool story – Trackback from DotNetShoutout…