Sunday, November 25, 2012

dynamic keyword in C# 4


The "dynamic" keyword-Working with compiled .NET types is easy in C#
-Type information is available through Reflection
-- It is possible to make runtime calls dynamically
When a decision about calls and call targets is made at runtime, we talk about “dynamic dispatch", or “late binding"
Other language platforms have their own dynamic dispatch techniques (Python, Ruby, but also Automation, Web Services, ...)
--"dynamic" builds a bridge to the Dynamic Language Runtime (DLR)
--The DLR unifies different dynamic dispatch approaches

First Impressions

dynamic i=4
dynamic s="Hi there";
i.DoS0methingImpossible();
Foreach (dynamic thing in things)
DoFal1(thing);


-"dynamic" is used in place of a type
-"dynamic" does NOT correspond to any type
-Runtime types of variables are similar to what you'd expect when using "var"
-Member access on variables declared "dynamic" IS deferred to runtime


Things that don't work
Deriving from "dynamic"
Implementing lEnumerab|e
Extension methods for “dynamic”
Remember: "dynamic" is not a type


Demo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynamicBasics
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic i = 42;
            dynamic s = "Hi thcrl";
            Console.WriteLine("Length of my string " + s.Length);
            //i.DoSomethingImp05sible( );
            var things = new dynamic[] { 42, "text value" };
            //dynamic k;
            foreach (dynamic item in things)
            {
                Console.WriteLine(item);
            }
            foreach (dynamic item in GetEnu())
            {
                Console.WriteLine(item);
            }

        }
        static IEnumerable GetEnu()
        {
            yield return "Hi there..";
            yield return 42;
            yield return true;
        }
        static void UseDynamicThing(dynamic thing)
        {
        }


        // The following code snippet is invalid
        //static void UseDynamicThing(var thing)
        //{
        //}
    }
    ///Inheriying from dynamic is not allowed
    ///
    //public class test : dynamic
    //{
    //}
}



The Reflection Misconception
-Dynamic dispatch through the DLR is quite fast
-The idea is obvious to replace mechanisms like Reflection with DLR dynamic dispatch
-The AP|s offered by the DLR don't make this easy
-The "dynamic" keyword makes it easy because the compiler does the work
-If information relevant to the dispatch is not available at compile time "dynamic" can't help

 

No comments: