Visual Basic .NET Late Binding Explored

In a previous post I mentioned how Visual Basic .NET's  lambda expressions are more fun and easy to use than C#'s.  My inspiration for this statement was the fact that in VB .NET you are able to implicitly define a lambda expression in this way:

 Dim f = Function(x) x + x
Console.WriteLine(f(5)) 'Outputs: 10
Console.WriteLine(f("matt")) 'Outputs: mattmatt

 

When I began looking at this I realized that the type of x was automatically set as Object.  That makes sense since its the most basic type but then I wondered how VB is resolving operations like x + x, x * x, and x.length when x is an Object.  VB can't know at compile time if those functions exists on the type stored in Object.

Visual Basic deals with these function calls on objects in two different ways. 

 

Mathematical Method call on Object

If the compiler sees that you are doing a recognized mathematical operation it will call the appropriate method from Microsoft.VisualBasic.CompilerServices.Operators.  This class defines methods such as AddObject which determines the type of the two object and checks if there is an addition operation defined for them, if so it will execute it.  If the types are not compatible or don't have addition defined on them an exception will be thrown.  Up to this point all of this work is done by using type checking and type casting.  If all of these tests then the objects will be reflected on in an internal function called InvokeUserDefinedOperator.  This function will figure out if this the type stored in the object type has the addition operator defined and if all is compatible execute it.  The heavy use of reflection is held off until it has to be used since it is much slower.  Doing the initial type checking and casting using a large table of known types is a big performance boost for this method since mathematical operates are usually used on standard .NET types.

 

Any other method call on Objects

In this case the optimization technique used above is not applicable so reflection must be used from the start.  To perform this reflection on the objects the Microsoft.VisualBasic.CompilerServices.NewLateBinding class is used.  This class defines methods which wrap many of the basic refection methods (it is not meant to be called directly from your code but I am not sure why that is).    The method LateGet is called on the objects with the given function and it is attempted to be called.  If it doesn't exist an exception is thrown, naturally.

 

This is just a brief look into how Visual Basic is using late binding to make lambda expressions easier to use.