Hi,
I want to make a function like CType but can't figure out how to do this.
Function ConvertWhithoutException(ByVal Item As Object, ByVal aType As Type)
As Object
Dim output As Object = Nothing
Try
output = CType(Item, aType)
Catch ex As Exception
End Try
Return (output)
End Function
But this doesn't compile.
Does anyone know how to make a function I can use in the same manner that I
can use the CType-function?
Thanks,
Filip
Mattias Sj?gren - 29 Oct 2004 21:52 GMT
Filip,
>I want to make a function like CType but can't figure out how to do this.
The short answer is that you can't.
> Catch ex As Exception
> End Try
You should never do this.
>Function ConvertWhithoutException(ByVal Item As Object, ByVal aType As Type)
>As Object
...
> Return (output)
And even if you could do what you want, what good would it do when the
return type of your function is Object? Then you'd still have to cast
the function's return value to the appropriate type.
What you probably should do is guard your CType by first using the
TypeOf..Is operator to check if the cast will succeed. In VB 2005 you
can also use the TryCast operator.
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Cor Ligthert - 30 Oct 2004 08:56 GMT
Filip,
In addition to Mattias
It makes in my opinion no sense what you want to do, you are not the first
one who wants to try to make a kind of "Variable" in the VBNet.
It makes no sense because doing that is the reason why scripting language
are slow, it needs mostly a lot of useless processing time while you know
exactly the object. When you want what you ask, than use a scripting
language or use late binding. What is in fact the same.
Late Binding searches for your proper object at run time and is therefore
much slower.
When your object has no match with the needed object it will of course even
not work.
You set latebinding on by Option Strict Off. What means in the current
VBNet versions by not setting it to On. That while the last is always
advices in the dotNet newsgroup because than there is with a VBNet program
no difference in performance with a C# program.
I hope this gives some idea's?
Cor.
"Filip D'haene" <filip.dhaene@apscomputers.be>
> Hi,
>
[quoted text clipped - 18 lines]
>
> Filip
Jay B. Harlow [MVP - Outlook] - 30 Oct 2004 17:16 GMT
Filip,
> Does anyone know how to make a function I can use in the same manner that
> I can use the CType-function?
Have you looked at System.Type.ChangeType?
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlr
fsystemconvertclasschangetypetopic.asp
> Catch ex As Exception
> End Try
I agree with Mattias, this is rarely a good idea...
Be certain to read the documentation for Convert.ChangeType.
Hope this helps
Jay
> Hi,
>
[quoted text clipped - 18 lines]
>
> Filip