Skip to content

Purpose of this

amit_gupta14

Asked Mar 29, 2006, 9:28 PM EST1 answer
Share
LinkedInX

this: to represent current instance of class.
 
1st Usage: To qualify instance members otherwise hidden by parameters, as in the following:
public void SomeMethod (int hour)
{
this.hour = hour;
}
In this example, SomeMethod( ) takes a parameter (Hour) with the same name as a member
variable of the class. The this reference is used to resolve the name ambiguity. While this.Hour
refers to the member variable, Hour refers to the parameter.

2nd Usage:With indexers

3rd Usage: To pass the current object as a parameter to another method.
For instance, the following code
public void FirstMethod(OtherClass otherObject)
{
otherObject.SecondMethod(this);
}

I am not clear about 3rd usage type. What do you mean by "otherObject.SecondMethod(this);" and its usage?

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I dont know where you are getting these usages from, but the 3rd one is very important. It is a way when calling another class to reference yourself. There really isnt another way to put it. For example, you have a class called PeopleList and this class holds a list of all the people you know. Now lets says you call PeopleList.add("Joe"). Inside PeopleList it will add your new friend "Joe" to the list, but this makes the list unsorted and you want to keep the list sorted. Well, there just so happens to be another class called Sorter. So you want to call this class, but what is this Sorter class going to sort? If you were calling it from main you call pass the name of your PeopleList class into Sorter. But, it is the PeopleList class that is calling it, so how does the PeopleList class refer to itself? It calls Sorter.sort(this) and then it will pass the PeopleList class into the sorter.
    0