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
Update
Now I understand I have to use dynamic
keyword, but what use is this line if it's allowed
ExpandoObject myObj = new ExpandoObject();
You need to declare the variable as
dynamic
for this to work. That way the compiler will defer the assignment to theIDynamicMetaObjectProvider
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.