using ‘this’ keyword

Any time an object uses the this keyword, it’s referring to itself.  It’s a reference that points to the object that calls it. huh.

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

public void SpeakTo(Elephant whoToTalkTo, string message)
{
    whoToTalkTo.TellMe(message, this);
}
/*
Lloyd.SpeakTo(Lucinda, "Hello");
runs
 whoToTalkTo.TellMe(message, this); //this references Lloyd as the Elephant whoSaidIt object!!
which becomes
 Lucinda.TellMe(message, [a reference to Lloyd]); //this is replaced with a reference to Lloyd's object */

After writing this out and like an hour I finally get it. The resulting output will be “Lloyd says: Hello” because this is referencing the object that executed the method (in this case it was Lloyd executing the SpeakTo() method).  something something, may add more practical insight later.

On a side note I now use http://www.megatome.com/syntaxhighlighter/ for my source code examples. yay.

This entry was posted in Csharp. Bookmark the permalink.

Comments are closed.