Working With Expando Objects

The ExpandoObject class was introduced in .NET 4.0 which allows you to set properties on to an object at runtime. It's part of the Dynamic Language Runtime(DLR) and resides in System.Dynamic namespace. With expando objects it's possible to add and remove members at runtime.

A typical use case for expando object usage is when we need to return multiple values from a method. It's possible to use a hash list or a dictionary object for achieving the same, but then you need to do some additional coding to retrieve the values in the caller method. With expando object we can easily access the info just like any other object instances. 

You needs to import System.Dynamic first since we are using the dynamic keyword for creating an expando object. 

In the above snippet we have a private method called GetPersonInfo which returns personal info such as Name, Age, State, Country to the main method where we extract those info as properties of the returned instance and then writes to the console.

It's also possible to create complex structures with expando objects. Let's modify our earlier code to group all the address info into a complex object as shown below

In this case we have created another expando object to store address information and then set it's value to the address property in the Person instance. Now in the main class we can easily access all the properties and it's child ones just like any other object.

Another feature of the expando object is the support for raising events

Note : You may have noticed that I have used a $ symbol and used the members directly inside the string literal itself in the Console.WriteLine statement. That's the new string interpolation operation in C# 6.0 and you can read more about it here.


No Comments

Add a Comment