Information Technology Reference
In-Depth Information
The this Keyword
The this keyword, used in a class, is a reference to the current instance. It can only be used in
the blocks of the following class members:
￿
Instance constructors
￿
Instance methods
￿
Instance accessors of properties and indexers
Clearly, since static members are not part of an instance, you cannot use the this keyword
inside the code of any static function member. Rather, it is used for the following:
￿
To distinguish between class members and local variables or parameters
￿
As an actual parameter when calling a method
For example, the following code declares class MyClass , with an int field and a method that
takes a single int parameter. The method compares the values of the parameter and the field,
and returns the greater value. The only complicating factor is that the names of the field and
the formal parameter are the same: Var1 . The two names are distinguished inside the method
by using the this access keyword to reference the field.
class MyClass
{
int Var1 = 10;
Both are called "Var1"
public int ReturnMaxSum(int Var1)
{ Parameter Field
return Var1 > this.Var1
? Var1 // Parameter
: this.Var1; // Field
}
}
class Program
{
static void Main()
{
MyClass mc = new MyClass();
Console.WriteLine("Max: {0}", mc.ReturnMaxSum(30));
Console.WriteLine("Max: {0}", mc.ReturnMaxSum(5));
}
}
Search WWH ::




Custom Search