0 0
WP Ad Inserter plugin
Read Time:1 Minute, 45 Second

In C#, ExpandoObjects are dynamically-populated objects without a predefined shape.

dynamic myObj = new ExpandoObject();
myObj.Name ="Davide";
myObj.Age = 30;

Name and 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 ExpandoObject class.

Now: how can I retrieve all the values? Probably the best way is by converting the ExpandoObject into a Dictionary.

Create a new Dictionary

Using an 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 IDictionary:

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.

Cast to IDictionary

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 ExpandoObject implements 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

Wrapping up

Both approaches are correct. They both create the same Dictionary, but they act differently when a new value is added to the ExpandoObject.

Can you think of any pros and cons of each approach?

Happy coding!

🐧

Source: https://www.code4it.dev/csharptips/expandoobject-to-dictionary

Useful Tools for Creating AVIF Images Previous post Useful Tools for Creating AVIF Images
Backup Plugin Battle: Which is the Best WordPress Backup Plugin in 2022? Next post Backup Plugin Battle: Which is the Best WordPress Backup Plugin in 2022?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.