How to convert a string value to a data type during runtime ?

J

JC Voon

Hi:


I need to convert a value reading from XML file to specific type,
the XMLstring is look like this:

<Field1 DataType="System.Int32", Value="123">


Dim t As Type = Type.GetType("System.Int32")

Dim i as integer = CType("123", t ) ---> the 2nd param not accept t

Any idea ?

Thansk
JCVoon
 
T

Tom Shelton

Hi:


I need to convert a value reading from XML file to specific type,
the XMLstring is look like this:

<Field1 DataType="System.Int32", Value="123">


Dim t As Type = Type.GetType("System.Int32")

Dim i as integer = CType("123", t ) ---> the 2nd param not accept t

Any idea ?

Thansk
JCVoon

Dim i As Integer = Convert.ToInt32 ("123")
Dim i As Integer = Integer.Parse ("123")
 
A

Armin Zingler

JC Voon said:
Hi:


I need to convert a value reading from XML file to specific type,
the XMLstring is look like this:

<Field1 DataType="System.Int32", Value="123">


Dim t As Type = Type.GetType("System.Int32")

Dim i as integer = CType("123", t ) ---> the 2nd param not accept t

Any idea ?


System.String implements the IConvertible interface. Check out it's ToType
function:

Dim t As Type = Type.GetType("System.Int32")
Dim o As Object = DirectCast("123", IConvertible).ToType(t, Nothing)


o is declared "as Object" because you don't know the type. If you would know
it, you could declare it 'as integer' and use CInt or Integer.Parse.


Armin
 
P

Phill. W

JC Voon said:
Dim t As Type = Type.GetType("System.Int32")
Dim i as integer

Essentially, what you /want/ to do is ...

i = Convert.ChangeType( "123", t )

.... but, perversely, ChangeType() returns an Object which you
then have to cast /again/, as in

i = DirectCast( _
Convert.ChangeType( "123", t ) _
)

HTH,
Phill W.
 
J

JC Voon

Hi TomShelton, Armin Zinger, Phill. W:

Thanks for the answer, both Armin and Phill. method is exactly what i
want.


Dim t As Type = Type.GetType("System.Int32")
Dim o As Object = DirectCast("123", IConvertible).ToType(t, Nothing)

and

Dim t As Type = Type.GetType("System.Int32")
Dim o As Object = Convert.ChangeType( "123", t )


Thanks
JCVoon
 

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