C# dynamic object initializer won't compile
Asked Answered
H

2

13

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.

Huttan answered 18/11, 2010 at 15:15 Comment(1)
Please vote for this feature in Visual Studio UserVoice.Lisette
F
13

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.

Frangipane answered 18/11, 2010 at 15:18 Comment(1)
Ah, yes that makes sense. The object initializer expression is not typed as dynamic.Huttan
H
7

In your first example, the C# compiler will look for a property named Test on the ExpandoObject. It doesn't exist.

In your second example, the compiler will look for a Test property on a dynamic object. This is allowed, so it compiles.

Horseshoe answered 18/11, 2010 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.