Friday, January 30, 2015

C# 4.0 – Dynamic Lookup

C# 4.0 introduce Dynamic Lookup to the C# feature set. Dynamic Lookup is the ability to resolve names in a program at runtime instead of compile time. VB 2008 already includes this feature which is sometime referred to as Late Binding.
Dynamic Lookup can be used for Office automation or COM Interop scenarios, consuming types written using dynamic languages or to provide enhanced support for reflection.
Previous versions of C# have been statically typed where type checking is performed at compile time. Dynamic Lookup allows this type checking to be performed at runtime (similar to Javascript or Ruby).

Dynamic Keyword

To support Dynamic Lookup , C# 4.0 introduces the dynamic keyword which may appear directly or as a component of a constructed type, for example:
  1. Dynamic keyword used as the  type of a property, local variable, indexer, field, return value, parameter, or type constraint:
    class EgClass
    {
        // Dynamic field.
        static dynamic field;
    
        // Dynamic property.
        dynamic prop { get; set; }
    
        // Dynamic return type plus dynamic paramater.
        public dynamic egMethod(dynamic d)
        {
            // Dynamic local variable.
            dynamic loc = "Loc variable";
            int three = 3;
    
            if (d is int)
            {
                return loc;
            }
            else
            {
                return three;
            }
        }
    }
  2. Dynamic keyword used in  explicit type conversions, as the target type of a conversion:
    static void convert2Dynamic()
    {
        dynamic dyn;
        int i = 30;
        dyn = (dynamic)i;
        Console.WriteLine(d);
    
        string str = "Sample string.";
        dyn = (dynamic)str;
        Console.WriteLine(dyn);
    
        DateTime todayNow = DateTime.Today;
        dyn = (dynamic)todayNow;
        Console.WriteLine(dyn);
    
    }
    // Output:
    // 30
    // Sample string.
    // 4/1/2010 9:19:00 AM
  3. The Dynamic Keyword can be used in any context where types serve as values. For example as the argument to typeof as part of a constructed type, or on the right of an is operator or an as operator:
    int i = 9;
    dynamic dyn;
    // With the is operator the dynamic type acts like object.
    if (aVar is dynamic) { }
    
    // With the as operator.
    dyn = i as dynamic;
    
    // With typeof, as part of a constructed type.
    Console.WriteLine(typeof(List<dynamic>));
    
    // The following statement causes a compiler error.
    //Console.WriteLine(typeof(dynamic));

No comments:

Post a Comment