CSharp - Type Creation dynamic type

Introduction

Dynamic binding defers binding operations from compile time to runtime.

A dynamic type is declared with the contextual keyword dynamic:

dynamic d = GetSomeObject();
d.Walk();

The existance of Walk method is verified during the runtime not the compile time.

Demo

using System;
using System.Dynamic;

public class Test
{
       static void Main()
       {//from  w  w w .  j ava2  s.  com
         dynamic d = new Person();
         d.Walk();                  // Walk method was called
         d.Talk();                 // Talk method was called
       }
}

public class Person : DynamicObject
{
       public override bool TryInvokeMember (
         InvokeMemberBinder binder, object[] args, out object result)
       {
         Console.WriteLine (binder.Name + " method was called");
         result = null;
         return true;
       }
}

Result

Dynamic Conversions

The dynamic type has implicit conversions to and from all other types:

int i = 7;
dynamic d = i;
long j = d;        // No cast required (implicit conversion)

The preceding example worked because an int is implicitly convertible to a long.

The following example throws a RuntimeBinderException because an int is not implicitly convertible to a short:

int i = 7;
dynamic d = i;
short j = d;      // throws RuntimeBinderException