The keyword "this" is always used to reference the current instance.
Code:
public class Foo
{
public void DoSomething()
{
MyTargetClass myObj = new MyTargetClass();
myObj.DoSomethingWith(this);
}
public void Bar()
{
}
}
public class MyTargetClass
{
public void DoSomethingWith(Foo foo)
{
foo.Bar();
}
}
The DoSomething method is an instance method of the Foo class. this is used within members of the class to reference the current instance of the class.
The DoSomethingWith method of the MyTargetClass class is declared to receive an object of type Foo as its parameter. Thus within the DoSomething method the current instance that is of type Foo can be passed to the DoSomethingWith method, and within the DoSomehingWith method every public member of Foo can be accessed.
That's very similar with properties:
Code:
private string someData;
public string SomeData
{
get
{
return this.someData;
}
set
{
this.someData = value;
}
}
SomeData is an instance property of a class. With the this keyword you access the current instance. With this.someData you access the field someData that is defined as an instance field.
In this scenario you could also write it this way:
Code:
private string someData;
public string SomeData
{
get
{
return someData;
}
set
{
someData = value;
}
}
Using the this keyword just gives a better readability to show an instance member is used instead of a local variable. The this keyword must be used in cases if there is a local variable with the same name to define the instance member is used instead of the local variable.
Hope this helps.