I have the following code
public class Base {
public Base() {}
public virtual void IdentifyYourself() {
Debug.Log("I am a base");
}
public void Identify() { this.IdentifyYourself(); }
}
public class Derived : Base {
public Derived() {}
public override void IdentifyYourself() {
Debug.Log("I am a derived");
}
}
I run the following test code in a different entrypoint:
Base investigateThis = new Derived();
investigateThis.Identify()
and the output is: "I am a derived"
So no matter where the C# 'this' keyword is used; does it always refer to the run-time type no matter what scope 'this' is used in?
Bonus points to anyone who was able to 'Google' better than me and find MSDN documentation on specifically 'this' (pun intended) behavior.
Lastly, does anyone happen to know what is happening under the hood? Is it just a cast?
Update #1: Fixed typo in code; With the current set of answers, I guess I did not fully understand the implications of what the MSDN documentation meant by "..is the current instance..".
Update #2: Apologies, I wasn't sure if I should have made a separate question, but on further investigation, I've confused myself again; given this updated code, why is the output both: "I am a derived" & "It is a base!".
Didn't other people answer that 'this' is indeed the run-time type? Let me know if my updated question still is not clear.
Updated code:
public class Base {
public Base() {}
public virtual void IdentifyYourself() {
Debug.Log("I am a base");
}
//Updated the code here...
public void Identify() { this.IdentifyYourself(); AnotherTake(); }
public void AnotherTake() { WhatIsItExactly(this); }
public void WhatIsItExactly(Derived thing) {
Debug.Log("It is a derived!");
}
public void WhatIsItExactly(Base thing) {
Debug.Log("It is a base!");
}
}
public class Derived : Base {
public Derived() {}
public override void IdentifyYourself() {
Debug.Log("I am a derived");
}
}