How to CType() when target type's name is in a string

D

Don

Let's say I have a type name stored in a string (e.g. Dim typeName As String
= "Decimal"). Is it possible to CType() a variable to the type whose name
is stored in that string?

e.g.

Dim typeName As String = "Decimal"
Dim source as String = "3"
Dim target as Decimal

target = CType(source, <magic happens with typeName> )


Is there maybe another method that does this, instead of CType()?
 
M

Mythran

Don said:
Let's say I have a type name stored in a string (e.g. Dim typeName As
String = "Decimal"). Is it possible to CType() a variable to the type
whose name is stored in that string?

e.g.

Dim typeName As String = "Decimal"
Dim source as String = "3"
Dim target as Decimal

target = CType(source, <magic happens with typeName> )


Is there maybe another method that does this, instead of CType()?

You might be able to using reflection, but when it's a known type, wouldn't
using "if" statements be faster?

HTH,
Mythran
 
H

Herfried K. Wagner [MVP]

Don said:
Let's say I have a type name stored in a string (e.g. Dim typeName As
String = "Decimal"). Is it possible to CType() a variable to the type
whose name is stored in that string?

e.g.

Dim typeName As String = "Decimal"
Dim source as String = "3"
Dim target as Decimal

target = CType(source, <magic happens with typeName> )

Performing a cast ('DirectCast') would not make much sense. Its advantage
is type checking at design time, not at runtime. However, you can use
'Convert.ChangeType' for converting values between types:

\\\
Dim b As Object = Convert.ChangeType(a, Type.GetType(...))
///
 
D

Don

Mythran said:
You might be able to using reflection, but when it's a known type,
wouldn't using "if" statements be faster?

The "known type" was just an example.
 
D

Don

Herfried K. Wagner said:
Performing a cast ('DirectCast') would not make much sense. Its advantage
is type checking at design time, not at runtime. However, you can use
'Convert.ChangeType' for converting values between types:

\\\
Dim b As Object = Convert.ChangeType(a, Type.GetType(...))
///

Thanks. I'll look into Convert.ChangeType()

- Don
 

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

Top