Skip to main content

DLR-Expando Object


ExpandoObject Class


This class represents an object whose members can be dynamically added and removed at run time.

This class implements the following intefaces
IDynamicMetaObjectProvider
IDictionary
ICollection>
IEnumerable>
IEnumerable
INotifyPropertyChanged

(for details about these interfaces please go theough MSDN documentation)



The ExpandoObject class enables developer to add and delete members of its instances at run time.
This class is also used to set and get values of these members.
It  supports dynamic binding, which enables developers to use standard syntax rather than  more complex complex syntax that are currently used.
For example:
consider an object _Pobj which has associated member named MyMember
It can be invoked as _Pobj.MyMember rather than _Pobj .GetAttribute("MyMember").



The ExpandoObject class implements the standard Dynamic Language Runtime (DLR) interface IDynamicMetaObjectProvider, which enables to share instances of the ExpandoObject class between languages that support the DLR interoperability model.


In C#, to enable late binding for an instance of the ExpandoObject class, the dynamic keyword is used.

Example:

dynamic myexpandoobject= new ExpandoObject();
//Adding New Members

//properties, methods, and events can be added to instances of the myexpandoobject class.


sampleObject.testdynamicProperty = "MyDynamicProperty";


Here we are adding testdynamicProperty property dynamically to myexpandoobject(object of ExpandoObject Class).


Let's go through another example that shows how to add an event to an instance of the ExpandoObject class.



class MySampleClass
{
    MySampleClass()
    {
        dynamic addeventobject= new ExpandoObject();


        // Create a new event and initialize it with null.
        addeventobject.EventToBeAdded = null;


        // Add an event handler.
       addeventobject.EventToBeAdded += new EventHandler(MyEventHandler);


        // Raise an event for testing purposes.
        addeventobject.EventHandler(addeventobject, new EventArgs());
   }


    // Event handler.
    static void MyEventHandler(object sender, EventArgs e)
    {
        //Code for handling event
    }
}


Let's try to explore some more aspects in which the expando object can be used.
1.Passing ExpandoObject as Parameter
2.Enumerating and Deleting Members



Passing ExpandoObject as Parameter

Like any other ordinary object, expando can be passed as a parameter to the methods.
(not to forget the dynamic keyword)

Example:

class ParameterPassingTest
{
    ParameterPassingTest()
    {
       
    }


   public void CreateObject()
   {
        dynamic developer, Projectmanager;

       
       developer= new ExpandoObject();
        developer.Name = "Pradeep Patel";
        developer.Age = 27;


        Projectmanager = new ExpandoObject();
        Projectmanager.Name = "PM";
        Projectmanager.Age = 38;
        Projectmanager.TeamSize = 25;


        WritePerson(developer);
        WritePerson(Projectmanager);
   }


    private static void WritePerson(dynamic details)
    {
        Response.Write("{0} is {1} years old.",details.Name, details.Age);
             
    }
}


In the above exaple, if developer object is passed and we try to access the TeamSize property on this object an exception will occur i.e.If we write details.TeamSize , while passing developer object.


It become very obvious that we need to take some extra care while dealing with expando objects(during the initial phases, when we are just learing its usage)


Enumerating and Deleting Members


Enumeration


As mentioned in the beginning, the ExpandoObject class implements the IDictionary interface.
This enables enumeration of members added to the instance of the ExpandoObject class at run time.

Now let's write another example to test enumeration of expando object elements by casting an instance of the ExpandoObject class to the IDictionary interface and enumerate the instance's members.
 

dynamic sse= new ExpandoObject();
sse.Name = "Pradeep Patel";
sse.Age = 27;
sse.Qualification="B.Tech";
string details=string.Empty;

foreach (var property in (IDictionary)sse)
{
   details+=property.Key + ": " + property.Value)+"";
}

(Please not the code is only for illustration purpose and has not been optimized ofr checked)

Deletion

C# does not have any sntax for deleting members hence developers need to cast an instance of the ExpandoObject to the IDictionary, before deleting any member.

Following code snippet shows the same

dynamic sse = new ExpandoObject();
employee.Name = "Pradeep";
((IDictionary)sse).Remove("Name");

ExpandoObject class is inevitable in achieving the dynamic functionality offered in the new framework.
Hoever this falls shot when we need to have our custom dynamic objects.

DynamicObject class provide this functionality, which will be covered in the next article.


Hope this was Helpful.

Till Next time we connect......

Happy Coding 

Comments

Popular posts from this blog

Asp.Net 4.0: An Overview-Part-III

This is the last post in the series which will explore the following new features of ASP.Net 4.0  Performance Monitoring for Individual Applications in a Single Worker Process Web.config File Refactoring Permanently Redirecting a Page Expanding the Range of Allowable URLs Performance Monitoring for Individual Applications in a Single Worker Process It is a common practice to host multiple ASP.NET applications in a single worker process, In order to increase the number of Web sites that can be hosted on a single server. This practice results in difficulties for server administrators to identify an individual application that is experiencing problems. ASP.NET 4 introduces new resource-monitoring functionality introduced by the CLR. To enable this functionality, following XML configuration snippet is added to the aspnet.config configuration file.(This file is located in the directory where the .NET Framework is installed ) <?xml version="1.0" encoding="UTF-8...

Covariance and Contravariance-General Discussion

If you have just started the exploration of .Net Framework 4.0, two terms namely Covariance and Contravariance might have been heard. The concept that these terms encapsulate are used by most developer almost daily, however there has never been any botheration about the terminologies. Now, what actually these terms mean and how are these going to affect us as a developer, if we dive in to the details. The simple answer is it’s always good to know your tools before actually using them. Enough philosophy, let’s get to the business. Starting the discussion let me reiterate that in addition to Covariance and Contravariance, there is another terminology, Invariance. I’ll by start here by diving into the details of Invariance and then proceed further. Invariance: Invariance can be better understood by considering the types in .Net.>net has basically two type, value-types and reference-types. Value types (int, double etc) are invariant i.e. the types can’t be interchanged either ...

Advanced WCF

In this post, I am sharing the link of articles about  advanced topics in WCF. The List of articles is exhaustive and can serve as your repository for all WCF queries. Concurrency,Throttling & Callbacks  WCF Concurrency (Single, Multiple and Re entrant) and Throttling   WCF-Interop and BinarySecurityToken  WCF Callbacks  Creating Web Services From WSDL Link1 Link2 Link3 Link4 WCF-Security WCF over HTTPS   Transport Security(basic)/HTTPS UserNamePasswordValidator ServerCertificateValidationCallback 9 simple steps to enable X.509 certificates on WCF - CodeProject http://www.codeproject.com/KB/WCF/9StepsWCF.aspx?display=Print Message Security(Certificate)/PeerTrust Securing WCF Services with Certificates. - CodeProject http://www.codeproject.com/KB/WCF/wcf_certificates.aspx Message Security(Certificate)/ChainTrust How To Configure WCF Security Using Only X.509 Certificates - CodePr...