C# Dynamic Binding – Custom Binding

Custom binding is a form of dynamic binding which occurs when a dynamic object implements IDynamicMetaObjectProvider (IDMOP). Whilst you can implement IDynamicMetaObjectProvider on types that you which are written in C#, the more common use-case is that you have been given an IDMOP object from a dynamic language (such as IronPython or IronRuby) that is implemented in .NET on the DLR.

Objects languages that implicitly implement IDMOP as a method to directly control the meanings of operations performed on them. The below code demonstrates the use of custom binding:

using System;
using System.Dynamic;
public class CustomBindingTest
{
static void Main()
{
dynamic dObj = new Dog();
dObj.Bark(); // Bark method was called
dObj.Run(); // Run method was called
}
}
public class Dog: DynamicObject
{
public override bool TryInvokeMember (
InvokeMemberBinder binder, object[] args, out object result)
{
Console.WriteLine (binder.Name + " method was called");
result = null;
return true;
}
}

In the above code the Dog class doesn’t actually have a Bark method, instead it uses custom binding to intercept and interpret all the method calls.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!