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.

Explanation
- We should mark object reference name with dynamic keyword to allow property to be added at runtime.
- In the R-value side, we create an instance of the DynamicExpando object.
- 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.

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.

Explanation
- 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.
- Next, we read all the property values from the dynamic object and display it in the console window.
5. Code Reference & Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Sample 00: Namespace Required using System.Dynamic; namespace CAshExamples { class Program { static void Main(string[] args) { //Sample 01: Create Dynamic Expando Object dynamic person = new ExpandoObject(); //Sample 02: Add Members at runtime person.Name = "Bill Gardo"; person.Age = 25; person.Sex = "Male"; //Sample 03: Read Properties Console.WriteLine("Person Name: " + person.Name); Console.WriteLine("Person Age: " + person.Age); Console.WriteLine("Person Sex: " + person.Sex); //Sample 04: Change the Age person.Age = 26; Console.WriteLine("Person Name: " + person.Name); Console.WriteLine("Person Age: " + person.Age); Console.WriteLine("Person Sex: " + person.Sex); } } } |
Output

Categories: C#
Tags: C# dynamic keyword, C# ExpandoObject