C# 4.0 Dynamic Extensions - A First Look

By Anoop Madhusudanan

Vote on HN
About .NET 4.0 Series - I'll be covering various aspects of .NET 4.0 and related technologies in these posts

If you havn't yet watched Ander's video on C# 4.0, watch it here, right now. http://channel9.msdn.com/pdc2008/TL16/ 

For me the most exciting part is the new dynamic dispatching features in C# 4.0. Dynamic dispatching provides a great way for resolving method calls at runtime. The new dynamic keyword can be used to create dynamic objects.


You can use dynamic keyword, if you want your method calls to be resolved only at the runtime.
dynamic invoker=new DynamicInvoker();
dynamic result1=invoker.MyMethod1();
dynamic result2=invoker.MyMethod2();
Here I'm implementing a dynamic invoker.


public class DynamicInvoker : IDynamicObject
    {
        public MetaObject GetMetaObject
              (System.Linq.Expressions.Expression parameter)
        {
            return new DynamicReaderDispatch (parameter);
        }
    }

    public class DynamicDispatcher : MetaObject
    {
        public DynamicDispatcher (Expression parameter) 
                   : base(parameter, Restrictions.Empty){ }

        public override MetaObject Call(CallAction action, MetaObject[] args)
        {
            //You'll get MyMethod1 and MyMethod2 here (and what ever you call)
            Console.WriteLine("Logic to invoke Method '{0}'", action.Name);
            return this; //Return a meta object
        }
    }

Watch out this space soon for a couple of practical examples. Dynamic dispatching has hell lot of possibilities, so that you can have wrappers around anything to execute your calls!!

Ander's video also covers PLINQ and a heart warming demo of C# Read-Eval-Print loop using Managed C# Compiler.


No comments:

Post a Comment

Please keep your comments clean.

© 2012. All Rights Reserved. Amazedsaint.com