Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat exactly is a CLR reference, and how does it hold type information?
    primarykey
    data
    text
    <p>My brain had a segfault this morning trying to understand exactly how and when C# can work out the type of an object from a reference to that object. Consider the following highly unoriginal example code:</p> <pre><code>class Foo { public virtual void Baz() { } } class Bar : Foo { } class Program { static void Main() { Foo f = new Bar(); f.Baz(); } } </code></pre> <p>The type of the reference there is Foo, but the object instance actually created is a Bar. That Bar instance has some overhead, i.e. a Sync Block index, and a reference to a MethodTable, presumably Bar's MethodTable. If you look at the Bar object on the heap, the only clue to its type is the MethodTable reference, which would suggest that it's a Bar.</p> <p>Onto the question then. Is there any way for C# to know from the actual object graph that 'f' is a Foo, and if so, how? Does the reference 'f' contain type information itself? When I call f.Baz(), am I right in thinking that the dispatch occurs via Bar's MethodTable anyway? Is it simply that case that the C# compiler uses flow analysis to work out what's going on and prevent any illegal operations? Does the CLR actually not care about the type declaration of Foo by the time it's been translated into IL?</p> <p>Apologies if that's a long-winded and poorly-phrased question - let me know if any clarification is required!</p> <p>TL;DR - How does a polymorphic reference in the CLR work? How is any discrepancy between the actual vs declared class type persisted, and could you tell what the original declaration was from the resultant IL?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload