Is this a hole in dynamic binding in C# 4?

Posted by Galilyou on Stack Overflow See other posts from Stack Overflow or by Galilyou
Published on 2010-05-05T15:25:27Z Indexed on 2010/05/05 15:28 UTC
Read the original article Hit count: 258

Filed under:
|

I've seen a very interesting post on Fabio Maulo's blog. Here's the code and the bug if you don't want to jump to the url. I defined a new generic class like so:

public class TableStorageInitializer<TTableEntity> where TTableEntity : class, new()
    {
        public void Initialize()
        {
            InitializeInstance(new TTableEntity());
        }

        public void InitializeInstance(dynamic entity)
        {
            entity.PartitionKey = Guid.NewGuid().ToString();
            entity.RowKey = Guid.NewGuid().ToString();
        }

    }

Note that InitializeInstance accepts one parameter, which is of type dynamic. Now to test this class, I defined another class that is nested inside my main Program class like so:

class Program
        {
            static void Main(string[] args)
            {
               TableStorageInitializer<MyClass> x = new TableStorageInitializer<MyClass>();
                x.Initialize();
            }
            private class MyClass
            {
                public string PartitionKey { get; set; }
                public string RowKey { get; set; }
                public DateTime Timestamp { get; set; }
            }
        }

Note: the inner class "MyClass" is declared private.
Now if i run this code I get a "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" on the line "entity.PartitionKey = Guide.NewGuid().ToString()".
The interesting part, though is that the message of the exception says "Object doesn't contain a definition for PartitionKey".
alt text

Also note that if you changed the modifier of the nested class to public, the code will execute with no problems. So what do you guys think is really happening under the hood? Please refer to any documentation -of course if this is documented anywhere- that you may find?

© Stack Overflow or respective owner

Related posts about c#

Related posts about dynamic