Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamic object initializer won't compile

Tags:

c#

dynamic

c#-4.0

The following code seems reasonable to me. It should create the object and then use the dynamic features to let me assign any properties I like. However the compiler says that "ExpandoObject does not contain a definition for Test". To which I say, "I know, that's the freaking point!"

dynamic example = new ExpandoObject
{
  Test = "fail"
};

Any ideas why csc isn't allowing this.

The alternative is to manually expand the code into individual property assignments.

dynamic example = new ExpandoObject();
example.Test = "fail";

Which is annoying when I have lots of properties to assign.

like image 349
Andrew Davey Avatar asked Nov 18 '10 15:11

Andrew Davey


1 Answers

Within the object initializer, the type is ExpandoObject, not dynamic, so you don't get dynamic functionality. After the initializer, you are operating on a variable of type dynamic and so dynamic functionality is available there.

like image 190
Kirk Woll Avatar answered Oct 27 '22 20:10

Kirk Woll