Main Site Documentation

Quick C# Question


#1

I know, you guys get tired of it, but I gotta ask…

So between books and code from projects and examples I see alot of objects defined with an “_” before them like: “_Serialport” or “_Razor”.

Is there a reason for the “" score or is it just a naming preference for coders. I guess I just haven’t seen an explanation for the "” but I see it in alot of code.

I am assuming that its just an easy way to name an object that has the same name for ease of identifying it???

Mike in MN


#2

It is just a naming convention typically used for private member variables that should not be accessed outside the current class.


#3

Thanks Hari, its hard to get all the details when they aren’t explained.

I have probably read or looked through a dozen C# books. Each one has something the other doesn’t, but you never really get it all. I suppse if a person went to school or worked in the programming environment, these little things would be easier to pick up on.

Mike in MN


#4

Adding or not ding “_” will not change how your code works. But is is sometimes easier to follow ways to make coding easier. Your programs are going to be to small to worry about any of this but when you have thousands of lines of code, adding _ to private variables make them easier to see, like making your constants all upper case, like MAX_IO_COUNT


#5

I am starting to get it.

I actually just got a WPF application to read and display temperature reading from the Panda and display it using an “DataReceived” event via RS232.

It’s a baby step I know, but all the naming conventions get me lost from one source to the next.

Everyone sharing code is invaluable, Thanks Everyone!

Mike in MN


#6

As a note, underscores are considered bad practice in C# by Microsoft and the industry in general.

See this page:
http://msdn.microsoft.com/en-us/library/ms229002.aspx

specifically: “Names of Type Members” http://msdn.microsoft.com/en-us/library/ms229012.aspx


#7

Thanks MarkH…

On a side note, I was just reading over the Joystick driver by Chris that I am looking at tackling next. Slowly but surely things are coming together.

Hopefully I can get all this terminology and definitions down.

Mike in MN

[italic]Edited because changed credit for Joystick driver[/italic]


#8

I don’t think they’re considered bad practice, and ReSharper will recommend underscores for private fields. What is considered bad practice is s_, for example, to denote a static field.


#9

It is funny, it is against MS practice, but you see many MS code with them.

The reason they are used is good intention. Many times, your private var names match the argument names in a ctor or method, so it is way to disambuiguate the two and has roots in other langs. .Net solved this problem with “this” keyword. However, even with the “this” keyword, it can be easy to forget using “this” and can cause some hard to find bugs in your program. So the “_” crowd trys to side-step the issue to make it obvious. I can understand the thought behind it, but I still can’t stand looking at them in code, so I either use “this.xxx” or change the private name to something different then the Arg names.


public class MyClass
{
    private string name
    public MyClass(string name) 
    {
        this.name = name; // ok.
        // name = name; // bug (with compiler warning)
        if (name == null) name = "";  // Bug. Did not assign name.
    }
}


#10

underscores do hark back to the c and c++ days, there is no real reason for them these days with visual studio giving you all the info you need in tooltips.

If you’ve named a parameter the same as a field or property, thats more a design issue than a code functionality issue :wink:


#11

Actually underscore’s go back to Microsoft C version 1… Underscore’s were used to differentiate between assembly identifiers and C identifiers. As everyone has said there really is no need for them nowaday’s

I think people assume its an advanced programming thing!

Some people use the underscore when they need to use a keyword or a reserved word as an identifier for readability’s sake…

Cheers Ian


#12

In constructors and such, I often (usually) name fields and properties with the same name. Then when I set or access them I use “this”. Like so:

this.field = field;

If they refer to the same thing they get the same name.

-Eric


#13

While there may be no ‘need’ for conventions like the underscore nowadays it does allow one to look at a bunch of code and immediately know what is what. Using verbose object names is a huge help too, what does some thing like ‘_g1’ tell you about its purpose? Nothing. While ‘accelPhase1’ gives you a more clear idea of what the object is but not where it lives, whereas ‘_accelPhase1’ gives you both bits of information in a quick glance. At some point though the additional markup included in a name becomes a hindrance. I for one am not in a big hurry to go back to Hungarian notation. :wink:


#14

I was reading thru’ an O’Reilly book on C# from 2003 recently and the author undertook a little diversion into the rationale behind naming conventions.

MS have a real problem because of all that legacy code that is not just being dragged around, but is still actually used. The advice the authors came up with was (I think) pretty sensible.

When you’re writing code that someone else might use, use Pascal Name notation ( System.Xml.XmlTextWriter) in preference to CamelCaps (system.xml.xmlTextWriter), with the exception of interfaces, which should have a capitalized ‘I’ in front of them.

ALL CAPS for pragmas and constants, avoid underscores, and if you’re interfacing with COM or COM+, obey their old naming conventions because if you’re interfacing with COM, you’ll be familiar with them.

Bits of code that aren’t exposed outside of quite restricted scope, they suggest you do whatever you want, except for public members that will be exposed to calling code.

I personally avoid moving outside of standard printable ASCII purely to avoid (as much as possible) the ‘Turkish I problem’, which I’d never heard of before, but just confirms to me that y’all can’t be too careful, even with what looks like ASCII on the page.

It took me a LONG time to fully abandon underscores.


#15

@ Mog
"When you’re writing code that someone else might use, use Pascal Name notation ( System.Xml.XmlTextWriter) in preference to CamelCaps (system.xml.xmlTextWriter), with the exception of interfaces, which should have a capitalized ‘I’ in front of them."

I might simplify it further. Every name is camel case. Either upper camel or lower depending on type.

Namespace - upper camel
Class - upper camel
Interface - upper camel
Property - upper camel
Enum - upper camel
struct - upper camel
Public field - upper camel
field - lower camel
parameter - lower camel

So it turns out to be pretty easy to remember. non-public fields and parameters are lower camel, everything else is upper camel.


#16

An excellent book on such subjects is Framework Design Guidelines. I recommend it for anyone interested in creating production code and especially public code or API’s. It not only tells you that you should do things but most importantly why.


#17

That’s what I’ve come to in course of my development career. I’ve tried different styles and variations thereof. The only exception to this - and this will make MarkH cringe - is for module variables I prefix with an underscore.

I’m using a lot of MVVM lately, and in the view model there quite a bit of private fields to hold public property values, private module and method variables. The underscore helps to differentiate between module and method variables.

Also in local private methods I lower camel, this differentiates it from the method variable and variables with a module scope.


class ThisVM : INotifyPropertyChanged
{
	public event PropertyChangedEventHandler PropertyChanged;

	int _moduleVariable;

	int _myValue;
	public int MyValue
	{
		get 
		{ 
			return _myValue; 
		}
		set 
		{ 
			_myValue = value; 
			raisePropertyChanged("MyValue"); 
		}	
	}	

	public void DoSomething()
	{
		bool changed; /// just for example sakes
		change = true;
		_moduleVariable++;
	}

	void raisePropertyChanged(string Name)
	{
		if (PropertyChanged != null)
			PropertyChanged(this, new PropertyChangedArgs(Name));
	}
}


#18

The official Microsoft guideline is :

But I guess “_” is more used than “this.”


#19

Along the lines of “this”, only use it when actually necessary. Do not use it for every time to refer to a member variable.


#20

@ Chris : StyleCop has a rule asking to prefix with this. all " instance member of the local class or a base class"

http://www.thewayithink.co.uk/stylecop/sa1101.htm