Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0158 ExpandoObject Dynamic Type

You can dynamically add properties just by assigning values to ExpandoObject Dynamic Type. Note that the instance of ExpandoObject is declared using the dynamic keyword. The following example creates an ExpandoObject and writes out the property values: using System; using System.Dynamic; public class MainClass { static void Main(string[] args) { dynamic my = new ExpandoObject(); my.Name = "Jack"; my.Age = 34; my.Address = new ExpandoObject(); my.Address.Street = "Main Street"; my.Address.City = "New York"; // Access the members of the dynamic type. Console.WriteLine("Name: {0}", my.Name); Console.WriteLine("Age: {0}", my.Age); Console.WriteLine("Street: {0}", my.Address.Street); Console.WriteLine("City: {0}", my.Address.City); // Change a value. my.Age = 44; // Add a new property. my.Address.Country = "US"; Console.WriteLine("\nModified Values"); Console.WriteLine("Age: {0}", my.Age); Console.WriteLine("Sister: {0}", my.Address.Country); } } The output: Name: Jack Age: 34 Street: Main Street City: New York Modified Values Age: 44 Sister: US