since many years i'm trying to figure out that what does 'this' do in c#.net
e.g.
private string personName;
public Person(string name)
{
this.personName = name;
}
public override string ToString()
{
return this.personName;
}
}
The this
keyword allows you to explicitly refer to a member of the current instance.
In your case, you can just as easily leave it off - the rules in C# will find the member variable.
However, if you use a parameter with the same name as a member variable, or have a local with the same name, using this
specifies which variable to use. This allows you to do:
private string personName;
public Person(string personName)
{
// this finds the member
// refers to the argument, since it's in a more local scope
this.personName = personName;
}
Tools like StyleCop enforce the use of this
everywhere, since it completely removes any ambiguity - you're explicitly saying you want to set a member (or call a function, etc) within the current instance.
this
refers to the object that the method belongs to. It can be used - like demonstrated in the other answers - for scope choosing. It can also be used when you want to use the current object as an entire object(that is - not a specific field, but the object as a whole) - for example:
public class Person{
private string name;
private Person parent;
public Person(string name,Person parent=null;){
this.name = name;
this.parent = parent;
}
public Person createChild(string name){
return new Person(name,this);
}
}
this
refer to the instance of the class. Usually you don't use it as it becomes noise,but in some case it's important to use it.
public class Foo
{
private string bar;
public Foo(string bar)
{
//this.bar refer to the private member bar and you assign the parameter bar to it
this.bar = bar;
//Without the this, the bar variable in the inner scope bar, as in the parameter.ΒΈ
//in this case you are assigning the bar variable to itself
bar = bar;
}
}