In this article, I would like to share extensible dynamic object in C#, we all have idea about dynamic and extensible object in scripting language. C# .net 4.0 introducing dynamic type that provides a host of dynamic features for the static C# language. With the dynamic keyword, one interesting object comes out to be ExpandoObject.
C# .NET 4.0 has a cool new ExpandoObject class, in the System.Dynamic namespace. It provides very dynamic object that allows you to add properties and methods on the fly and then access them again.
For example, you can do like
dynamic school = new ExpandoObject();
school.Id = 001;
school.Name = "St.Xavier";
//Nested dynamic instance
school.address = new ExpandoObject();
school.address.city = "Gandhinagar";
school.address.state = "Gujarat";
//Bind dynamic Event
school.HelloWorld = (Func<string, string>)((string name) =>
return "Hello " + name;
Real time use:
Before send rest call response if you want to perform any data structure modification like split data in two different formats (no need makes separate class)
Before send rest call response if you want to set hierarchical data structure of your multiple query output. E.g.:
Query-1 output with list of state and Query-2 output with list of cities. If you want set output in state>>city hierarchical structure like as below it just possible without making separate class.
As cool as ExpandoObject is it has a few limitations too:
- It is a sealed type so you can not use it as a base class
- It only works off ‘properties’ in the internal Dictionary – you can’t expose existing type data