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

Authentication using Social Networking portals(Facebook, Gmail, and Yahoo)

There are tons of sites, which offer sign on using the social networking site credentials (Facebook, gtalk, twitter and the list continues).It can be termed a “SINGLE SIGNON” and offers a lot of benefits compared to traditional database authentication approach. However, not storing user credentials in the DB imposes an additional risk. How to track who all logged into the system. Now the question is, which approach to follow. The best approach is to use inbuilt asp.net users for storing the logging info about user activities and using single signon technique for authentication. This article will explore the approach and provide the details of implementation using some third party libraries and customizing it to the requirements. The Authentication will be done using the following networking portals Yahoo  Gmail Facebook    Special thanks to my friend Sumit Khandelwal, for implementation of Facebook part (in fact he did it all!!) Except Facebook, all other ca...

WPF Overview-Part-II

This post is in continuation to the last post. In this Post I’ll be exploring the Dependency Properties Dependency properties are similar to CLR properties with more advanced and complex features. The main difference between the CLR properties and dependency properties is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject . In case this description did not make sense, no need to worry, It will become clear by the time you reach end of this article. How the Value is Resolved in Dependency properties Every time a dependency property is accessed, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not, check if a custom style trigger is active and I the similar manner continues until it finds a value. At last the default value is alwa...

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