4

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?

aush
  • 2,108
  • 1
  • 14
  • 24
  • Related: http://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation – Frédéric Hamidi Mar 12 '13 at 14:33
  • 2
    Just to clarify your terminology: a *variable* knows only what its type restriction is. A variable of reference type can have a *value* which is a *valid reference* to an *object* (or a null reference, to no object.) It is the *object* that knows what its runtime type is. – Eric Lippert Mar 12 '13 at 14:57
  • The concept behind it is called [polymorphism](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming). – nvoigt Mar 12 '13 at 15:17
  • possible duplicate of [How do virtual methods work in C#?](http://stackoverflow.com/questions/3311012/how-do-virtual-methods-work-in-c) – H H Mar 12 '13 at 15:22

2 Answers2

8

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

sll
  • 61,540
  • 22
  • 104
  • 156
4

You want to know how runtime method binding works, that is, how does the runtime know to call one method M instead of another when there was not enough information at compile time to encode into the program precisely which method to call?

Here's a good exercise: try to write a program that has that behaviour without using the feature as it is already written in the runtime. By doing that you will gain insight into how the people implementing the runtime did it.

I go through this exercise for virtual functions here:

http://blogs.msdn.com/b/ericlippert/archive/2011/03/17/implementing-the-virtual-method-pattern-in-c-part-one.aspx

Read that series and you'll see how you could emulate virtual dispatch in a language that does not have it. The basic idea that I show in the articles is more or less how virtual dispatch actually works in C#. Interface dispatch is a bit trickier in practice but the concept is basically the same.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067