In my previous article, we discuss what is dynamic binding and when to use dynamic binding. Today we achieve custom dynamic binding using IDynamicMetaObjectProvider(IDMOP) interface. You can implement IDMOP(IDynamicMetaObjectProvider) on types that we write in C#; the most typical case is to acuire an IDMOP object from a dynamic language that’s implemented in .NET on the DLR, such as IronPython or IronRuby. In these languages objects internally implement IDynamicMetaObjectProvider as a means by which to directly control the meanings of operations performed on them. Let’s discuss it with a simple example in C#. Open Microsoft Visual Studio and create simple console application as shown below.
using System;
using System.Dynamic;
namespace CustomDynamicCSharp
{
class Program
{
static void Main(string[] args)
{
dynamic d = new Company();
d.GetEmployee();
d.GetEmpSal();
Console.ReadLine();
}
}
public class Company : DynamicObject
{
public void GetEmployee()
{
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
Console.WriteLine(binder.Name + " method called");
result = null;
return true;
}
}
}
As shown above, we are calling GetEmployee() method of Company class by using dynamic object d; we are also calling GetEmpSal() method which is not available in Company class. But runtime won’t produce any error because our Company class is implementing DynamicObject.