Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You’re thinking way too complicated.</p> <blockquote> <p>Does the reference 'f' contain type information itself?</p> </blockquote> <p>No. It doesn’t have to. It is simply an address to the beginning of the <code>Bar</code> object’s memory that was constructed earlier. <em>That</em> object contains a virtual method table (and possibly a reference to its associated <code>Type</code> object<sup>1</sup>, but that’s irrelevant here).</p> <blockquote> <p>When I call f.Baz(), am I right in thinking that the dispatch occurs via Bar's MethodTable anyway?</p> </blockquote> <p>Yes.</p> <blockquote> <p>Is it simply that case that the C# compiler uses flow analysis to work out what's going on and prevent any illegal operations?</p> </blockquote> <p>Flow analysis is complex and completely unnecessary here. The compiler allows exactly those operations that are allowed for the declaration type of <code>f</code> – which is <code>Foo</code>. The compiler doesn’t <em>care</em> about the actual (= dynamic) type of <code>f</code> at all.</p> <blockquote> <p>could you tell what the original declaration was from the resultant IL?</p> </blockquote> <p>Depends. An <em>object</em> doesn’t <em>have</em> a static type so “telling its static type at runtime” is meaningless. Declarations, on the other hand, differ. If the variable is a formal parameter of a method then sure, you can (at runtime) use reflection to determine the declaration type of the method’s parameter.</p> <p>For local variables, once again this operation is meaningless. On the other hand, the IL <em>does</em> store this information (as metadata?) via <code>.locals</code> so the code <em>can</em> theoretically be reverse engineered (Cecil and Reflector do this) to get the static type of variables.</p> <hr> <p><sup>1</sup> I’m guessing here but this is actually <em>improbable</em>. If each object held its own reference to an associated <code>Type</code> object, that would mean an additional overhead of a pointer. Additionally, this reference is entirely unnecessary, since the object can simply call <code>GetType</code> on itself to get its type. <code>GetType</code> does only need to be implemented once for each class (kind of a static method, really) and is dispatched via the usual virtual function table. Thus only <em>one</em> reference to a <code>Type</code> is required per class, as opposed to per object.</p>
 

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