views:

862

answers:

3

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.

A: 

CallByName will use reflection. So, I don't know if there is any other way.

Could you describe the scenario in which you are using CallByName?
That will help determine, if you need CallByName or something else.

shahkalpesh
+1  A: 

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
Tom Winter
"Cecil Has a Name" is correct about CallByName not caching anything. If you are repeatedly calling the same methods this way, you'll want to cache the type information in some way. Things can really slow down if you don't.
Tom Winter
A: 

If the CallByName function does not cache method bindings, it would be far better to write your own dispatch class that stores a hashtable to map name strings to MethodInfo objects.

Cecil Has a Name