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...

WCF-REST Services-Part-II

HOW REST is implemented in WCF Part-I of the series explored the REST conceptually and this post will explore how REST is implemented in WCF. For REST implementation in WCF, 2 new attributes namely WebGetAttribute and WebInvokeAttribute are introduced in WCF along with a URI template mechanism that enables you to declare the URI and verb to which each method is going to respond. The infrastructure comes in the form of a binding ( WebHttpBinding ) and a behavior ( WebHttpBehavior ) that provide the correct networking stack for using REST. Also, there is some hosting infrastructure help from a custom Service¬Host ( WebServiceHost ) and a ServiceHostFactory ( WebServiceHostFactory ). How WCF Routes messages WCF routes network messages to methods on instances of the classes defined as implementations of the service. Default behavior ( Dispatching ) for WCF is to do this routing based on the concept of action. For this dispatching to work, an action needs to be present in ev...

WPF Routing

WPF (3.5) introduced the concept of Routing that made the event routing easies in the scenarios where it was tedious to handle events. Consider a scenario where there are a number of Hyperlinks in a Panel that direct to separate locations on Click. Now if this is done in normal programming, each hyperlink will have to have code for execution. It would be easier and cleaner if we could handle the hyperlinks in the container (the Panel) that handles the click and redirects to appropriate location. WPF handles the events with the following 3 strategies. Direct events are like ordinary .NET events. They originate in one element and don’t pass to any other. For example, MouseEnter is a direct event. Bubbling events are events that travel up the containment hierarchy. For example, MouseDown is a bubbling event. It is raised first by the element that is clicked. Next, it is raised by that element’s parent, and then by that element’s parent, and so on, until WPF reaches the top of the e...