CType question

  • Thread starter Thread starter Filip D'haene
  • Start date Start date
F

Filip D'haene

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
 
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
 
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top