The this Keyword
The keyword this refers to the current instance of an object. The this reference is a hidden parameter in every nonstatic method of a class (we’ll discuss static methods shortly). There are three ways in which the this reference is typically used. The first way is to qualify instance members that have the same name as parameters, as in the following:
public void SomeMethod (int length)
{
this.length = length;
}In this example, SomeMethod( ) takes a parameter (length) with the same name as a member variable of the class. The this reference is used to resolve the ambiguity. Whereas this.length refers to the member variable, length refers to the parameter.
You can, for example, use the this reference to make assigning to a field more explicit:
public void SetBox(int length, int newWidth, int newHeight)
{
this.length = length; // use of "this" required
this.width = newWidth; // use of "this" optional
height = newHeight; // use of "this" not neededIf the name of the parameter is the same as the name of the member variable, you must use the this reference to distinguish between the two, but if the names are different (such as newWidth and newHeight), the use of the this reference is optional.
Tip
The argument in favor of naming the argument to a method that is the same as the name of the member is that the relationship between the two is made explicit. The counterargument is that using the same name for both the parameter and the member variable can cause confusion as to which ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access