How does a variable know about the type that it implements?

As I know, every variable knows about its type of runtime.

Here is an example:

void Main() { C c = new C(); cM(); I i = (I)c; iM(); } public interface I { void M(); } public class C : I { void IM() { Console.WriteLine("IM"); } public void M() { Console.WriteLine("M"); } } 

If I understand correctly, i still know that its type is C So, what is the mechanism that allows i to decide on using IM instead of M ?

+4
source share
2 answers

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

Here's a good exercise: try writing a program that has this behavior without using this function, as it is already written at runtime. By doing this, you get an idea of ​​how people who implement the runtime did.

I am doing 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 this series and you will see how you can emulate virtual sending in a language that does not have it. The main idea that I show in the articles is more or less how virtual dispatching actually works in C #. Interface dispatching is somewhat more complicated in practice, but the concept is basically the same.

+4
source

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

MSDN - Insert .NET Framework Internal Environments to learn how the common language runtime creates runtime objects

enter image description here

+8
source

All Articles