ExpandObject In C# 4.0

In this short blog, I will explain about the ExpandoObject in C# 4.0,. It's really dynamic.

Introduction To ExpandoObject

ExpandoObject is like an expand property in HTML. Microsoft has introduced a new class ExpandoObject. It's a really dynamic object. It is part of DLR (dynamic language runtime).
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
You can read more about ExpandoObject at MSDN.
Purpose: To create a runtime instance of any type. You can add properties, methods, and events to instances of the ExpandoObject class.


Here, we are creating a dynamic instance.
  1. dynamic Employee = new ExpandoObject();  
  2. Employee.ID = 1;  
  3. Employee.Name = "Amit";  
  4. Employee.Salary = 10000;  
  5. Nested dynamic instance  
  6. Employee.Addess = new ExpandoObject();  
  7. Employee.Addess.City = "Pune";  
  8. Employee.Addess.Country = "India";  
  9. Employee.Addess.PinCode = 456123;  
  10. Bind dynamic Event  
  11. Employee.Click += new EventHandler(SampleHandler);  
  12. private void SampleHandler(object sender, EventArgs e) {  
  13.     //throw new NotImplementedException();  
  14. }  
  15. Pass parameter as dynamic.  
  16. public void Write(dynamic employee) {  
  17.     //you can write your logic  
  18. }  
Happy coding