Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of CallbyName Function in VB.NET?

Are there any disadvantages in performance by using the CallByName function in VB.NET? Is there any better way to do the call by Name in .NET 2.0 onwards.

like image 250
Greens Avatar asked Aug 12 '09 17:08

Greens


1 Answers

CallByBame basically gives you "late binding" which is "figuring out the method at run-time" as opposed to "early binding" where the compiler figures it out for you.

With early binding you can be type safe and you'll have better performance since your code will go right to the method. The compiler will have "looked it up" for you ahead of time.

With late binding performance is slower since the method is looked up at run time and you don't have type safety - which means the method may not actually exist and you could get an exception. But this might be handy if you don't know the type of the object for some reason. I also use it to call COM object if I don't want to mess with an interop assembly.

CallByName most likely calls Type.InvokeMember. If you want to do it directly, here's some code I came up with:

Imports System.Reflection   ' For access to BindingFlags '

Friend NotInheritable Class LateBinding

    Private Const InvokePublicMethod As BindingFlags = BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.InvokeMethod

    Private Const GetPublicProperty As BindingFlags = BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.GetProperty

    Public Shared Function InvokeFunction(ByVal oObject As Object, ByVal sName As String, ByVal ParamArray yArguments() As Object) As Object

        Return oObject.GetType().InvokeMember(sName, InvokePublicMethod, Nothing, oObject, yArguments)

    End Function

    Public Shared Function GetProperty(ByVal oObject As Object, ByVal sName As String, ByVal ParamArray yArguments() As Object) As Object

        Return oObject.GetType().InvokeMember(sName, GetPublicProperty, Nothing, oObject, yArguments)

    End Function

End Class
like image 168
Tom Winter Avatar answered Oct 23 '22 16:10

Tom Winter