ExpandoObject class in C# 4.0

As you know till now in c# everything was static and known at design time. But with the C# 4.0  language Microsoft have enabled new dynamic data type which is belongs to Dynamic Language Runtime on top of CLR(Common language Runtime). As you know that dynamic object will know their behaviour at run time. Here Microsoft has given one new class called ExpandoObject class. ExpandoObject class is a member of System.Dynamic namespace and is defined in the System.Core assembly. This class object members can be dynamically added and removed at runtime. This is class is a sealed class and implements number of interfaces like below.
1.public sealed class ExpandoObject :
2.  IDynamicMetaObjectProvider,
3.  IDictionary<string, object>,
4.  ICollection<KeyValuePair<string, object>>,
5.  IEnumerable<KeyValuePair<string, object>>,
6.  IEnumerable,
7.  INotifyPropertyChanged;
Now let’s take a simple example of console application. Where we will create a object of expandoobject class and manipulate that class at run time. Let’s create a simple code like below.
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.namespace ExpandoObject
07.{
08.    class Program
09.    {
10.        static void Main(string[] args)
11.        {
12.            dynamic users = new System.Dynamic.ExpandoObject();
13.            users.UserName = "Jalpesh";
14.            users.Password = "Password";
15. 
16.            Console.WriteLine(string.Format("{0}:{1}","UserName:",users.UserName));
17.            Console.WriteLine(string.Format("{0}:{1}","Password:",users.Password));
18. 
19.            Console.ReadKey();
20.        }
21.    }
22.}
Here in the above code I have added a new memeber called UserName and Password for the new dynamic user type and then print their value. Now let’s run the application and see its output as below
ExpandoObject
That’s it. You can add valid type of member to ExpandoOjbect class. Isn’t interesting.. Hope you liked it.. Stay tuned for more..

0 comments:

Post a Comment