C# Dynamic Binding – Language Binding

Language binding is a form of dynamic binding which occurs when a dynamic object does not implement IDynamicMetaObjectProvider. Language binding comes in handy when working around imperfectly designed types or the inherent limitations in the .NET type system. A common problem is that when using numeric types is they have no common interface. Using dynamic binding, methods can be bound dynamically and the same also applies for operators:

static dynamic Mean (dynamic xObj, dynamic yObj)
{
return (xObj + yObj) / 2;
}
static void Main()
{
int xObj = 3, yObj = 4;
Console.WriteLine (Mean (xObj, yObj));
}

The benefit here is clear — you can avoid duplicating code for each numeric type. However, in doing so you will lose static type safety, risking runtime exceptions as opposed to getting compile time errors.
Note that dynamic binding only circumvents static type safety, runtime type safety is still perserved. In contrast when using reflection, you cannot circumvent member accessibility rules using dynamic binding.

Language runtime binding behaves very similarly to static binding when the runtime types of the dynamic objects are known at compile time. In the above example, the behavior of the program would be identical if Mean was hardcoded to work with the int type.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

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