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.

1
  • 2
    Please vote for this feature in Visual Studio UserVoice. Commented Feb 6, 2015 at 20:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, yes that makes sense. The object initializer expression is not typed as dynamic.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.