IntroductionIn this article, i will explain how to use the How to use ExpandoObject Class in .NET 4.0.The ExpandoObject class is introduced on .NET Framework 4.0 and inherited using many interfaces.and moreover 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 a sealed class and see below implmenetation of the ExpandoObject, public sealed class ExpandoObject :
IDynamicMetaObjectProvider,
IDictionary<string, object>,
ICollection<KeyValuePair<string, object>>,
IEnumerable<KeyValuePair<string, object>>,
IEnumerable,
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. How to use using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExpandoObject
{
class Program
{
static void Main(string[] args)
{
dynamic users = new System.Dynamic.ExpandoObject();
users.UserName = "CodeGain";
users.Password = "Password";
Console.WriteLine(string.Format("{0}:{1}","UserName:",users.UserName));
Console.WriteLine(string.Format("{0}:{1}","Password:",users.Password));
Console.ReadKey();
}
}
}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 Output That’s it. You can add valid type of member to ExpandoOjbect class.Enjoy it. |