Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Dynamic ExpandoObject in C#

1. Dynamic ExpandoObject

In the previous article, we learned about Anonymous Type to define properties at runtime. But these properties are read only and the type will not allow changing it after creation. C# provides a class called DynamicExpando which will also allow adding the properties at runtime. But we can read and write the property values at runtime with this object. Since the type allow adding the members on the fly, the compiler will not perform any type checking. We can also notice that Intellisence also will not provide any suggestion while typing the code. The ExpandoObject is exposed by ‘System.Dynamic’ namespace. In this example, we will learn about DynamicExpando object.

2. Creating ExpandoObject

In the below code snippet, we are creating the ExpandoObject and assigning three properties to it.

Fig 1. Create Expando Object
Fig 1. Create Expando Object

Explanation

  1. We should mark object reference name with dynamic keyword to allow property to be added at runtime.
  2. In the R-value side, we create an instance of the DynamicExpando object.
  3. At runtime, we add three property members Name, Age and Sex. Also note that Age is binding to a number and Name, Sex are binding to chain of characters.

3. Reading Property Values

After creating the DynamicExpando object, we can read its property values using dot operator. In the below code example, we read all three property members and display it in the console output window. Note, when you type the code, visual studio will not offer any Intellisence help.

Fig 2. Reading Data From Dynamic Expando Object
Fig 2. Reading Data From Dynamic Expando Object

4. Edit Dynamic ExpandoObject

In the below code snippet, we change the value of a property from the DynamicExpando object. Unlike, Anonymous Type, the expando will allow changing the property values.

Fig 3. Changing the Value of Dynamic ExpandoObject
Fig 3. Changing the Value of Dynamic ExpandoObject

Explanation

  1. Here, in this code snippet, we pick the dynamically cooked member Age and change its value from 25 to 26. This is allowed in Dynamic ExpandoObject.
  2. Next, we read all the property values from the dynamic object and display it in the console window.

5. Code Reference & Output

Output

Dynamic Expando Example Output
Dynamic Expando Example Output

Categories: C#

Tags: ,

Do you like this Example? Please comment about it for others!!

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