Dynamic Binding - CSharp Custom Type

CSharp examples for Custom Type:dynamic type

Introduction

A dynamic type is declared with the contextual keyword dynamic:


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

Since d is dynamic, the compiler defers binding DynamicMethod to d until runtime.

Static Binding Versus Dynamic Binding

Demo Code

using System;//from www  . j  ava  2s.  c  o m
using System.Dynamic;
public class Test
{
   static void Main()
   {
      dynamic d = new Duck();
      d.DynamicMethod();                  // DynamicMethod method was called
      d.AnotherDynamicMethod();                 // AnotherDynamicMethod method was called
   }
}
public class Duck : DynamicObject
{
   public override bool TryInvokeMember ( InvokeMemberBinder binder, object[] args, out object result)
   {
      Console.WriteLine (binder.Name + " method was called");
      result = null;
      return true;
   }
}

Result

Duck class doesn't have a DynamicMethod method. It uses custom binding to intercept and interpret all method calls.


Related Tutorials