The this
keyword refers to the current instance of class(object). That way two variables with the same name, one at the class-level (a field) and one being a parameter (or local variable) of a method, can be distinguished.
public MyClass {
int a;
void set_a(int a)
{
//this.a refers to the variable defined outside of the method,
//while a refers to the passed parameter.
this.a = a;
}
}
Other usages of the keyword are chaining non-static constructor overloads:
public MyClass(int arg) : this(arg, null)
{
}
and writing indexers:
public string this[int idx1, string idx2]
{
get { /* ... */ }
set { /* ... */ }
}
and declaring extension methods:
public static int Count<TItem>(this IEnumerable<TItem> source)
{
// ...
}
If there is no conflict with a local variable or parameter, it is a matter of style whether to use this
or not, so this.MemberOfType
and MemberOfType
would be equivalent in that case. Also see base
keyword.
Note that if an extension method is to be called on the current instance, this
is required. For example if your are inside a non-static method of a class which implements IEnumerable<>
and you want to call the extension Count
from before, you must use:
this.Count() // works like StaticClassForExtensionMethod.Count(this)
and this
cannot be omitted there.