First off, I did google this before hand but most of the answers I got were about assigning attributes, but that's the the trouble I'M having. I'M trying to understand the "this" keyword beging used as a parameter/argument.

Here some sample code

There is a class by the name Elephant.

Elephant lloyd = new Elephant() { Name = "Lloyd", EarSize = 40 };
Elephant lucinda = new Elephant() { name = "Lucinda", EarSize = 33 };

public void TellMe(string message, Elephant whoSaidIt)
{
MessageBox.Show(whoSaidIt.Name = "says: " + message);
}

public void SpeakTo(Elephant talkTo, string message)
{
talkTo.TellMe(message, this);
}

lucinda.SpeakTo(lloyd, "Hello");

According to the book I'M reading, Lucinda's talkTo parameter of the SpeakTo method has a reference to Lloyd's TellMe method. I don't see it. When where and how dos talkTo point to Lloyds TellMe?

According to the method definition for "tellme" that you show here, the 2nd param is of type Elephant. Which happens to be the type of the class that holds that method.

So when you call Tellme, and pass to it "this" you are passing a reference to the instance of an elephant class that the method is called from.

so when you call
lucinda.SpeakTo(lloyd, "Hello");
what is happen is, this method uses, lloyd(an instance of an Elephant) to get to its TellMe method. When you call the Tellme method of lloyd, you pass to lloyd the original method, but then it wants to know WHO sent that message(who called that method) So you say "THIS" since "THIS" is called from inside lucinda, THIS = lucinda who is of type elephant.

Sorry if I am confusing you. I hope you get it.

"this" always refers to the class you call it from.
If you are inside of a class, and you call "this" you are referring to the particular instance of that class as it is called at runtime.

So. if you are in lucinda, and you call "this" than this = lucinda.
if you are in lloyd and you call "this" than this = lloyd.

Also, the parameters aren't named very well to be easily undestood.
Instead of "talkTo" it should be ElephantToTalkTo. So when you pass lloyd, to the method, you are passing the elephant reference.

Edited 6 Years Ago by Diamonddrake: n/a

Comments
Nice explanation.

It may be a little bit vague but hope it will help you...

Firstly you created an instance of the Elephant class:

Elephant lloyd = new Elephant() { Name = "Lloyd", EarSize = 40 };

so the variable lloyd is now containing the reference to that object.
Then using:

lucinda.SpeakTo(lloyd, "Hello");

you passed the reference to lloyd.
SpeakTo function got the reference to lloyd. As the function is declared as follows:

public void SpeakTo(Elephant talkTo, string message)

locally talkTo refer to lloyd.
So, using:

talkTo.TellMe(message, this);

you refer to lloyd function TellMe.

This article has been dead for over six months. Start a new discussion instead.