I played with some C # statements in LINQPad to figure out what the middle language code emits.
First I tried the following code:
var Container = new {Name = "James"}; Console.WriteLine(Container.Name);
And I saw the following six lines of IL emitted:
IL_0001: ldstr "James" IL_0006: newobj <>f__AnonymousType0<System.String>..ctor IL_000B: stloc.0 IL_000C: ldloc.0 IL_000D: callvirt <>f__AnonymousType0<System.String>.get_Name IL_0012: call System.Console.WriteLine
Which, in general, I expect, and a pretty nice demonstration of how anonymous types are read-only / immutable, since the set_Name property is missing.
Next I tried the instructions:
dynamic Container = new System.Dynamic.ExpandoObject(); Container.Name = "James"; Console.WriteLine(Container.Name);
Because of this, a huge amount of IL occurs. I will not embed it here, but you can find it in this pastebin .
I understand that there is quite a lot of overhead to managing the dynamic type and ExpandoObject, but I donβt understand why it seems that the call to System.Console.WriteLine in this case is done through internal reflection.
IL_0072: ldstr "WriteLine" .... IL_00BF: ldtoken System.Console
In the first code segment, after the property was restored and saved, it was an IL single-line statement that called System.Console.WriteLine .
So why is all this necessary for a call of type dynamic ?