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

In previous few posts[ Introduction to Dynamic Type , Overloading with dynamic and Dynamicobject Class ] we explored new type dynamic in c# 4.0.
In System.Dynamic namespace, Microsoft introduced many classes related to dynamic language support in c#. One of the main class is ExpandoObject, which according to MSDN is defined as: “Represents an object whose members can be dynamically added and removed at run time.”
The ExpandoObject class is an implementation of the dynamic object concept that enables getting, setting, and invoking members.
Lets do some testing on this class.

dynamic calculator = new ExpandoObject();

            // Set properties
            calculator.Name = "Shahzad's Calulator....";
            calculator.Made= "Cesco";
            calculator.Price = 100;

            // Add methods
            calculator.AddNumbers = new Action<int, int>((i1, i2) => Console.WriteLine("Result for AddNumbers : {0}", (i1 + i2)));

            // Show state
            Console.WriteLine("Properties: Name:{0} , Made:{1}  , Price:{2}", calculator.Name, calculator.Made, calculator.Price);

            // Call method
            calculator.AddNumbers(5, 6);

            //Listing all properties
            Console.WriteLine("Listing all properties");
            foreach (var property in (IDictionary<String, Object>)calculator)
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }

            // Remove property
            ((IDictionary<String, Object>)calculator).Remove("Name");

            //Listing all properties
            Console.WriteLine("Listing all properties- After Removal of Name");
            foreach (var property in (IDictionary<String, Object>)calculator)
            {
                Console.WriteLine(property.Key + ": " + property.Value);
            }

            Console.WriteLine("Lets see: " + calculator.Color); //'System.Dynamic.ExpandoObject' does not contain a definition for 'Color'

            Console.ReadLine();

Comments explain everything.

Reference: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.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: