Re: Direct Cast or CType.
You can use either and you can use TryCast as well. If you know for a fact that the object will be type Button (or any type derived from Button) then you should use DirectCast. If you're not sure what type the object will be, i.e. the method may be used to handle events of other types too, then you should use TryCast, which will return Nothing if the cast fails rather than throwing an exception. CType performs additional type checking and will convert the object to the specified type if required and a valid conversion exists. There is no way that you want to be performing any object conversions in that code so CType should not be used. Doing so would not cause a problem but does not serve a purpose.
Re: Direct Cast or CType.
Also, that DirectCast is a little bit better performing since it doesnt do the type checking/validation.
Re: Direct Cast or CType.
Thanks guys, I just read something that said dicerctcast performs almost twice as good as Ctype when passing by value and more than twice as good when passing by reference, also that Ctype will convert two different types (ie Integer to String) that are derived from the same base type (object in this case) if it can find a conversion method, where direct cast would fail...
So this leads me to beleive that you shouldnt really have to use CType at all, as it will only use a known conversion method that is also available to the programmer.
Would it be safe to assume that quality coding would avoid CType as it will be slower and will use the same conversion methods available to the user, take this for example....
Code:
Sub Dosomething(byval obj as object)
if TypeOf obj Is String Then
msgbox(DirectCast(Obj, String))
ElseIf TypeOf obj is Integer then
msgbox(Cstr(DirectCast(obj, Integer)))
Else
msgbox("It was an unknown object")
End If
End Sub
'Instead of
msgbox(Ctype(obj, string))
So if I understand right, the above sub should be faster than Ctype even with the If Statement because Ctype is going to have to make that decision anyway, but it will also have to consider every other type, so if it was the last type in its list of possible conversions then it would be much slower, and this is actually better than the CType Function.... Am I getting it?
Thanks....
Re: Direct Cast or CType.
Yes, that code will be slowwer then using CType. If you are receiving an object of type "Object" in your arguments then you really should be using CType.