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.
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; }); Console.WriteLine(school.Name); Console.WriteLine(school.HelloWorld(".net"));
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.
<State> <id>1</id> <name>Gujarat</name> <city> <iscapital>true</iscapital> <City_Name>Ganhinagar</City_Name > </city> <city> <iscapital>false</iscapital> <City_Name>Bhavnagar</City_Name > </city> </state>
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
Click Here to explore all the technology categories on which our authors write an articles
As .Net developer 5+ years of experience , having knowledge different Microsoft technologies and scripting framework like C#, Asp.Net, jQuery, SQL Server, ADO.Net, XML Processing, angular, MVC, WEB API, WCF. Knowledge and industry experience with complete software development life cycles: analyzing the requirements, designing, and writing of implementation specifications, coding, testing. Good skills in preparing project timeline and providing project estimation and efforts.
I love to write complex logic and provide solution.
2 comments
How can we read an xml into C#? is there any xml tutorial where we can get reference?
Thanks in advance.
Yes, you can use this reference to read xml using jquery. They have explained good with an example. I hope this will help you.
Thanks