ExpandoObjects are dynamically-populated objects without a predefined shape.
dynamic myObj = new ExpandoObject(); myObj.Name ="Davide"; myObj.Age = 30;
Age are not part of the definition of
ExpandoObject: they are two fields I added without declaring their type.
This is a dynamic object, so I can add new fields as I want. Say that I need to add my City: I can simply use
myObj.City = "Turin";
without creating any field on the
Now: how can I retrieve all the values? Probably the best way is by converting the
ExpandoObject into a
IDictionary makes it easy to access the keys of the object.
If you have an
ExpandoObject that will not change, you can use it to create a new
dynamic myObj = new ExpandoObject(); myObj.Name ="Davide"; myObj.Age = 30; IDictionary<string, object?> dict = new Dictionary<string, object?>(myObj); myObj.City ="Turin";
Notice that we use the
ExpandoObject to create a new
IDictionary. This means that after the Dictionary creation if we add a new field to the
ExpandoObject, that new field will not be present in the Dictionary.
If you want to use an IDictionary to get the
ExpandoObject keys, and you need to stay in sync with the
ExpandoObject status, you just have to cast that object to an IDictionary
dynamic myObj = new ExpandoObject(); myObj.Name ="Davide"; myObj.Age = 30; IDictionary<string, object?> dict = myObj; myObj.City ="Turin";
This works because
IDictionary, so you can simply cast to IDictionary without instantiating a new object.
Here’s the class definition:
public sealed class ExpandoObject : IDynamicMetaObjectProvider, IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, INotifyPropertyChanged
Both approaches are correct. They both create the same
Dictionary, but they act differently when a new value is added to the
Can you think of any pros and cons of each approach?