Skip to content
19/12/2008 / dimarzionist

“What dynamic does NOT do ” example

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.

Advertisements

One Comment

Leave a Comment
  1. Miguel / Dec 24 2008 09:52

    It still seems wrong :s

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: