Software Architecture-DynamicObject Class of System.Dynamic namespace in C# 4.0

In previous few posts[ Introduction to Dynamic Type and Overloading with dynamic] we explored new type dynamic in c# 4.0.
In System.Dynamic namespace of C# 4.0, Microsoft introduced many classes related to dynamic language support in c#.
One of the main class is DynamicObject Class, which according to MSDN is identified as: “Provides a base class for specifying dynamic behavior at run time.”
Lets see details about this class, on IDE click on DynamicObject(Go to definition). You will notice that this class can’t be instantiated because its constructor is protected. Secondly it has many virtual method for providing implementation about dynamic behavior by overriding in derived classes.
See below:

Lets do some testing of this concept, by deriving a class from it. (Modified version of MSDN sample)

public  class DynamicCalculator : DynamicObject
    {
        // The inner dictionary.
        Dictionary<string, object> dictionary
            = new Dictionary<string, object>();

        // This property returns the number of elements
        // in the inner dictionary.
        public int Count
        {
            get
            {
                return dictionary.Count;
            }
        }

        // If you try to get a value of a property 
        // not defined in the class, this method is called.
        public override bool TryGetMember(
            GetMemberBinder binder, out object result)
        {
            // Converting the property name to lowercase
            // so that property names become case-insensitive.
            string name = binder.Name.ToLower();

            // If the property name is found in a dictionary,
            // set the result parameter to the property value and return true.
            // Otherwise, return false.
            return dictionary.TryGetValue(name, out result);
        }

        // If you try to set a value of a property that is
        // not defined in the class, this method is called.
        public override bool TrySetMember(
            SetMemberBinder binder, object value)
        {
            // Converting the property name to lowercase
            // so that property names become case-insensitive.
            dictionary[binder.Name.ToLower()] = value;

            // You can always add a value to a dictionary,
            // so this method always returns true.
            return true;
        }
        /// <summary>
        /// provide a method calling machism
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="args"> input parameters</param>
        /// <param name="result">output parameters</param>
        /// <returns> bool resuklt of method call to caller< /returns>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            result = 0;
            bool IsFound = false;
            switch (binder.Name.ToLower())
            {
                case "add":
                    result = (int)args[0] + (int)args[1];
                    IsFound= true;
                    break;

                case "multi":
                    result = (int)args[0] * (int)args[1];
                    IsFound = true;
                    break;
            }
            return IsFound;
        }
    }
  

Notice here that basically, there is a dictionary maintained via overrided members TrySetMember and TryGetMember for setting and getting members. Simple…
Secondly TryInvokeMember provided implementation for calling methods dynamically.
Lets do some testing on this class as:

dynamic cal = new DynamicCalculator();
        // Setting members/propertie to dynamic class
        cal.Name = "Shahzad Calculator";
        cal.Made = "Cieco";
        cal.Price = 100;
        // Getting members/propertie so dynamic class
        Console.WriteLine("Members of DynamicCalculator: Name: " + cal.Name + "  Made: " + cal.Made + " Price: " + cal.Price);
        // Invoking call to methods
        Console.WriteLine("Result of Add is : " + cal.Add(5, 6));
        Console.WriteLine("Result of Multi is : " + cal.Multi(5, 6));
        // Console.WriteLine("Result is : " + cal.Sub(5, 6));  //'SystemDynamicApp.DynamicCalculator' does not contain a definition for 'Sub'

Comments explain everything.

Happy coding for Dynamic behavior in C# 4.0

Reference: http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: