Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does variable know about the type it implements?

Tags:

c#

As I know, each variable knows about its runtime type.

Here is an example:

void Main()
{
    C c = new C();
    c.M();
    I i = (I)c;
    i.M();
}

public interface I
{
    void M();
}

public class C : I
{
    void I.M() 
    {
        Console.WriteLine("I.M");
    }

    public void M() 
    {
        Console.WriteLine("M");
    }
}

If I understand it right, i still knows that its type is C. So, what is the mechanism which lets i to decide on using I.M instead of M?

like image 553
aush Avatar asked Dec 16 '22 13:12

aush


1 Answers

Internally each object has its own TypeHandle, see object internal structure below:

MSDN - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects

enter image description here

like image 138
sll Avatar answered Dec 18 '22 03:12

sll