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.
views:
862answers:
3CallByName 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.
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
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.