Reputation: 26396
Just trying out on dynamic objects and I encountered this compile error
ExpandoObject myObj = new ExpandoObject();
myObj.GivenName = "Testing";
System.Dynamic.ExpandoObject' does not contain a definition for 'GivenName' and no extension method 'GivenName' accepting a first argument of type 'System.Dynamic.ExpandoObject' could be found
Looking at MSDN: ExpandoObject, they actually did it differently - using dynamic
keyword
dynamic myObj = new ExpandoObject();
myObj.GivenName = "Testing";
What is the explanation for this? And is it possible to still assign values on the instance of myObj
without using dynamic
keyword? I looked if it has .SetProperty
but no.
Thanks
Now I understand I have to use dynamic
keyword, but what use is this line if it's allowed
ExpandoObject myObj = new ExpandoObject();
Upvotes: 2
Views: 1496
Reputation: 62532
You need to declare the variable as dynamic
for this to work. That way the compiler will defer the assignment to the IDynamicMetaObjectProvider
part of the variable and the property will be given the value you've specified.
By typing the variable as ExpandoObject
your specifying an actual type, and because of this the compiler won't use the dynamic aspects of the class.
Upvotes: 6
Reputation: 13266
Once you mark mark a variable as dynamic anything to do with that variable is happens at runtime. So, during compilation, the compiler is not aware of a property GivenName
as it is not present in the type ExpandoObject
. But when you declare it as dynamic the compiler will not worry about this variable and the binding happens at runtime.
You can find in detail how to implement a dynamic type at http://msdn.microsoft.com/en-us/vstudio/ff800651.aspx
Upvotes: 2