What does the underscore mean in C Sharp?

What does the underscore mean in C Sharp?

I saw a program,

Class Metals {
string _metalType;
public Metals(string type)
_metalType = type;
Console.WriteLine("Metal: " + _metalType);

What does the _ (underscore) mean in it?
Does that mean any static variable or something else?

It’s not a rule, it’s more of a convention. I think many folks use it to denote a private member in the class.

It’s another way to refer to private instance variables. Instead of typing this.metalType, some tend to prefer _metalType for some reason. Others use the m_metalType naming convention which is even worse.

this. is depreciated and not needed. if you really wanted to you could also do: this._metalType

_ means nothing in C#, it is just the name of the variable, would be exactly the same if you leave the _ out.

I’m not sure if I read it correctly or understand it, but when in the hell did “this.property” become deprecated in C#? Geez, I seem to be always behind the “proper way” curb. Then again, I have been using it in JavaScript and Literal Expressions.

Good to know, I guess.

You can use it, but it is not needed. It is a redundant qualifier.

It is only needed if your property has the same name as a method parameter, but that in itself is bad practice

Night, do you code in JS, if so, do you use “this”? I thought it was mandatory in order to access objects in Literal form. Or, where you only referring to C#?

I am only referring to C#. I usually use this in javascript as well. Not sure if its redundant or not in js

Is it really bad practice? I’ve learned that way and still use this sort of code:

private IPageRepository extrasRepository;
public PageItemsController(IPageRepository extrasRepository)
	this.extrasRepository = extrasRepository;

Well, according to me it is. I would start the private variable with _

I don’t mind agreeing with you, I just want to know why. :slight_smile: Who deprecated it?

I just thinks it varies from individual to individual, I do similar to imaginekitty

private IQueryable theSource;

public IQueryable TheSource
    get { return theSource; }
    set { theSource = value; }

_metalType is just the name of the variable, makes no difference if you write it without underscore like “metalType”.