0

I'm having trouble figuring out how to create array of dynamic generic ExpandoObject elements.

I started with this statement, which works:

/* WORKS */
dynamic expando = new ExpandoObject() as IDictionary<string,object>;

What I want is an array composed of such objects. The syntax I tried is this:

/* DOES NOT WORK */    
var expandoArray = new ExpandoObject[] as IDictionary<string, object>
{
    new ExpandoObject() as IDictionary<string, object>,
    new ExpandoObject() as IDictionary<string, object>
};

The idea is that after expandoArray is created, I could refer to its elements as a dynamic by using a construct like this (see http://weblog.west-wind.com/posts/2012/Feb/01/Dynamic-Types-and-DynamicObject-References-in-C):

dynamic expandoArrayDynamic = expandoArray[x];

So, my two specific questions are: 1. How do I create an array of Expando as IDictionary objects? 2. How do I view the array elements as dynamic objects?

7
  • ExpandoObject implicitly implementes IDictionary<string,object> and thus the cast isn't necessary. Commented Jun 5, 2016 at 16:25
  • Surely the cast ExpandoObject[] as IDictionary<string, object> is not valid, it should be like: ExpandoObject[] as IEnumerable<IDictionary<string, object>>? Commented Jun 5, 2016 at 16:26
  • You're completely misunderstanding the as keyword. Commented Jun 5, 2016 at 16:28
  • @Mike: As stated, the cast works (as shown in comment). Commented Jun 5, 2016 at 16:33
  • @SLaks: Not sure what you mean--the first code sample uses IDictionary<string, object> correctly. If it doesn't please explain rather than simply chastise. Commented Jun 5, 2016 at 16:34

1 Answer 1

2

Does this do what you want?

var expandoArray = new IDictionary<string, object>[]
{
    new ExpandoObject(),
    new ExpandoObject(),
};
Sign up to request clarification or add additional context in comments.

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.