Monday, February 06, 2012
 
   
 
Welcome to my site

First let me say thanks for stopping by my site. My name is David Hanson-Graville and I am a IT consultant working in the UK. Let me make it clear, I am passionate about technology and specifically .net and its various forms. I've programmed in a range of langages, but I can say, I am now at my happiest when coding with c#. I hope my blog is an enjoyable & educational read and please feel free to email me at David.Hanson@OnTheBlog.net if you have any questions. 

C# 4.0 and Dynamic Objects Part 1 Minimize
Location: BlogsOnTheBlog    
Posted by: David Hanson Thu, 13 Nov 2008 00:19:26 GMT

Over the last week I have been watching a number of sessions that were recorded at PDC. One that I particularly enjoyed was Anders Hejlsberg “Future of C#”.

During this talk Anders provides a brief introduction to dynamics support in C#. If you’re not sure what dynamics really are then the best way to describe it is the ability to perform lazy evaluation of an objects data type & members at runtime. To make this clearer we can look at C# as it stands today as a purely static language. If we define a new class within c# 3.5 show below we are generally bound to use only the members that have been defined on the contract.

    public class PlainOldObject

    {
        public string Name { get; set; }
        public int Age { get; set; }

    }

Now when it comes to using the PlainOldObject class we can only do so in a limited way as compilation will fail if we try to access properties that do not exist. Take for example

            PlainOldObject plainOldObject = new PlainOldObject();
            plainOldObject.Name = "Dave Hanson";
            plainOldObject.Age = 30;

            plainOldObject.FavouriteLanguage = "c#";

This fails compilation with an error of “'PlainOldObject' does not contain a definition for 'FavouriteLanguage'”. In order to get this code to compile in our current c# 3.5 code we need to go back to the class and implement a new property called FavouriteLanguage of type string.

Introducing the Dynamic Type

Dynamics support in c# 4.0 solves this issue for us! In C# 4.0 a new static type is being introduced called dynamic. The dynamic type tells the c# compiler to ignore type checking at compile and instead leave the evaluation until runtime. The dynamic type can be applied to any .net type but more importantly it can be applied to external resources such as XML, COM objects and Scripts.

So given we have late binding of members now supported in C# 4.0 with the use of the dynamic type what will our code example from above look like. This is show below.

            dynamic plainOldObject = new PlainOldObject();

            plainOldObject.Name = "Dave Hanson";
            plainOldObject.Age = 30;

            plainOldObject.FavouriteLanguage = "c#";

As you can see the code looks almost identical. Apart from the dynamic keyword nothing else has changed. However, under C# 4.0, when you go to compile you will not be faced with a compilation error as was shown before. At this point we can see that the compiler is no longer checking all the members of the type during compile but we are still faced with the issue that our PlainOldObject does not actually implement the property FavouriteLanguages. In fact, running the code will cause an exception to be throw. 

The next issue we need to solve is how we go about create a dynamic object that can be extended arbitrarily. To do this, we follow the approach most dynamic languages follow. As types have no fixed structure in dynamic languages they must store their data in a generic way, therefore they often implement an internal collection within the type which will store data for each dynamic property is set. Implementing this pattern in C# 4.0 is relatively straight forward.

Introducing DynamicObject

In order for us to create our own dynamic objects Microsoft have provides us with an abstract class called DynamicObject. This abstract class has a number of virtual methods which we can override and that provide interceptors for all method invocations, property getters and setters as well some other useful functions. This is shown below. 

    public abstract class DynamicObject : IDynamicObject
    {
        public virtual object GetMember(GetMemberBinder info);
        public virtual object SetMember(SetMemberBinder info, object value);
        public virtual object DeleteMember(DeleteMemberBinder info);
        public virtual object UnaryOperation(UnaryOperationBinder info);
        public virtual object BinaryOperation(BinaryOperationBinder info, object arg);
        public virtual object Convert(ConvertBinder info);
        public virtual object Invoke(InvokeBinder info, object[] args);
        public virtual object InvokeMember(InvokeMemberBinder info, object[] args);
        public virtual object CreateInstance(CreateInstanceBinder info, object[] args);
        public virtual object GetIndex(GetIndexBinder info, object[] indices);
        public virtual object SetIndex(SetIndexBinder info, object[] indices, object value);
        public virtual object DeleteIndex(DeleteIndexBinder info, object[] indices);
        public MetaObject IDynamicObject.GetMetaObject();
 

    }

So in order to allow our PlainOldObject to support dynamic behaviour we need to inherit the DynamicObject class and then override the GetMember and SetMember methods. In our implementation of these methods we need to ensure that if the SetMember is called we place a value into the internal dictionary of values held within PlainOldObject and if the GetMember is called we need to retrieve the value. Below is an example of this code. 

    public class PlainOldObject : DynamicObject
    {
        private Dictionary<string,object> _members = new Dictionary<string,object>();
 
        public override object GetMember(GetMemberAction member)
        {
            return _members[member.Name];
        }
 
        public override object SetMember(SetMemberAction member, object value)
        {
           _members[member.Name] = value;
        }

    }

And that’s it.... were done. We now have an extensible dynamic object that can be extended without having to implement new properties. 

            dynamic plainOldObject = new PlainOldObject();
            plainOldObject.Name = "Dave Hanson";
            plainOldObject.Age = 30;
            plainOldObject.FavouriteLanguage = "c#";
            plainOldObject.Height = 6.0;
            plainOldObject.Sex = "Male";
            plainOldObject.Foo = "Bar"
 
Permalink |  Trackback

Your name:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Tweets Minimize
Twitter / LordHanson
  1. LordHanson: #southeastern have once again proved their rolling stock can reach new lows.

    Published Wed, 01 Feb 2012 08:09:05 +0000 by
  2. LordHanson: Checked in at The Cards http://t.co/LANfHukb

    Published Sun, 29 Jan 2012 11:04:51 +0000 by
  3. LordHanson: @BillGates Run for president Bill.

    Published Fri, 27 Jan 2012 08:41:35 +0000 by
  4. LordHanson: @swhelband Again!

    Published Fri, 27 Jan 2012 08:39:44 +0000 by
  5. LordHanson: The update for the Nokia Lumia recently has done wonders for battery life! Good job #Nokia #windowsphone

    Published Fri, 27 Jan 2012 08:36:27 +0000 by
  6. LordHanson: Checked in at Victoria Station http://t.co/L0BJ5smd

    Published Thu, 26 Jan 2012 08:35:41 +0000 by
  7. LordHanson: @pdl_uk VAT No: 924 5933 08 Shoulder again! Dang!

    Published Wed, 25 Jan 2012 21:47:45 +0000 by
  8. LordHanson: @tommyjmquinn I think that would be easier. Next Thursday ok?

    Published Wed, 25 Jan 2012 21:04:46 +0000 by
  9. LordHanson: @tommyjmquinn London bridge doable?

    Published Wed, 25 Jan 2012 20:32:34 +0000 by
  10. LordHanson: @tommyjmquinn so where's the meet?

    Published Wed, 25 Jan 2012 19:04:02 +0000 by
  11. LordHanson: @tommyjmquinn your choice mate. Somewhere easy to get to from Bankside. :-D

    Published Tue, 24 Jan 2012 22:01:20 +0000 by
  12. LordHanson: @tommyjmquinn so Darius, Justin and me confirmed. Thursday good for you? Waiting to hear from Sal.

    Published Tue, 24 Jan 2012 21:47:21 +0000 by
  13. LordHanson: @mark_mann which is illegal I thought!

    Published Tue, 24 Jan 2012 21:46:17 +0000 by
  14. LordHanson: Details on Windows Phone 8 confirms NT kernel http://t.co/5Qg1MILl

    Published Tue, 24 Jan 2012 21:34:11 +0000 by
  15. LordHanson: But next target for framework is #winrt. Need to see if my dependencies like DI, RX, ReactiveUi etc will work. Hmm

    Published Mon, 23 Jan 2012 08:33:16 +0000 by
  16. LordHanson: @pdl_uk hey Phil, how's marathon training going?

    Published Mon, 23 Jan 2012 08:31:37 +0000 by
  17. LordHanson: So I now have a framework for apps which targets .net, Silverlight and windows phone. Thankyou project linker!

    Published Mon, 23 Jan 2012 08:28:08 +0000 by
  18. LordHanson: For some reason dropped twitter for a month. Can't say I missed it really. Maybe I need to broaden my follow list!

    Published Mon, 23 Jan 2012 08:24:44 +0000 by
  19. LordHanson: Soo much hype over SIRI when it came out yet I never see anyone use it and don't know anybody who does either. #apple #sooverhyped

    Published Mon, 23 Jan 2012 08:23:18 +0000 by
  20. LordHanson: #southeastern customer satisfaction survey given to me today. This should be fun! Bit wait......no extremely poor option! Just very poor.

    Published Mon, 23 Jan 2012 08:20:09 +0000 by
Print  
Archive Minimize
Print  
Contact me Minimize
Print  
Microsoft Certs Minimize







Print  
Silverlight News Minimize
Silverlight - Google News
  1. Windows Phone 8 - Silverlight Apps Are Legacy - iProgrammer

    Published Fri, 03 Feb 2012 13:03:27 GMT by
  2. Super Bowl Streaming Fail - StreamingMedia.com

    Published Mon, 06 Feb 2012 05:59:33 GMT by
  3. Delphi Developers Rejoice at Silverlight, FireMonkey and VCL Coming Together ... - San Francisco Chronicle (press release)

    Published Tue, 31 Jan 2012 17:34:58 GMT by
  4. WP7 Upgrades and WP8 - Silverlight or C++ - iProgrammer

    Published Tue, 31 Jan 2012 17:21:58 GMT by
  5. Watch The 2012 Super Bowl Online - SportsGrid

    Published Sun, 05 Feb 2012 23:15:21 GMT by
  6. US viewers can watch Super Bowl on Mac, iOS - Macworld

    Published Sun, 05 Feb 2012 20:22:31 GMT by
  7. Hydra 4 Sharpens Its Teeth, Breathes New Fire - Dr. Dobb's

    Published Sun, 05 Feb 2012 17:25:01 GMT by
  8. Will Silverlight live or die? Microsoft won't say - InfoWorld

    Published Fri, 27 Jan 2012 11:00:46 GMT by
  9. Cablevision Flips Live TV To Laptops With Microsoft Silverlight - Multichannel News

    Published Fri, 27 Jan 2012 17:24:53 GMT by
  10. Do SharePoint & Silverlight Have a Future Together? - CMSWire

    Published Mon, 16 Jan 2012 17:29:27 GMT by
Print