AMemberofDollars AMemberofDollars - 1 year ago 72
C# Question

Nuance of 'this' keyword regarding base and derived types

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();

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: 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 " the current instance..".

Answer Source

Absolutely! investigateThis refers to an instance of Derived.

So the virtual method IdentifyYourself in Derived will be called. This is run-time polymorphism in effect.

The scope does not matter.

Under the hood, an virtual function table is built, and there is a pointer in the object that points to that table.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download