There are several important concepts related to new dynamic types in C# 4.0 which could be a bit confusing without correct understanding of boxing/unboxing of value types that happens during the dynamic binding.
Here is good example from Sam Ng’s blog:
public struct S { public int i; } public class D { public S s; public static void Main() { dynamic d = new D(); d.s = default(S); d.s.i = 10; Console.WriteLine(d.s.i); }
We would intuitively expect the value ‘10′ to be printed in the console. However, the value ‘0′ is printed instead. Core thing is any of the dotted expressions were to bind to a value type, that value will be boxed (and hence a copy would be made), and further dots into it would be made on the copy of the value, and not the initial value as would be expected.
The guys from C# team currently on the way of investigation if it’s reasonable to add any smart compile time logic to handle things like this for dynamic usage. But from my perspective main thing is to understand the reason for this – real value type was unboxed during dotted expression and modified, but wasn’t(!) boxed again.
December 24, 2008 at 9:52 am
It still seems wrong :s