How do I convert from string to Type?

K

Ken Varn

I have an unknown numeric Type object passed into a function. I want to run
a conversion on a string to convert the string to that Type object and
return an object of that type. Is there some way to do a generic cast or
conversion on the type?

Here is sort of what I want to do:

object MyFunc(Type T, String Str)
{
object o;

o = // Want to convert Str to be of type T here.

return o; // Want to return an object of Type T here that has the
converted value.
}

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.

EmailID = varnk
Domain = Diebold.com
-----------------------------------
 
B

Bjorn Abelli

...
I have an unknown numeric Type object passed into a function.
I want to run a conversion on a string to convert the string
to that Type object and return an object of that type. Is
there some way to do a generic cast or conversion on the type?

Here is sort of what I want to do:

object MyFunc(Type T, String Str)
{
object o;

o = // Want to convert Str to be of type T here.

return o; // Want to return an object of Type T here that has the
converted value.
}

It's not obvious what you're trying to accomplish. As what your method
returns only is of the type "object", you'll probably still need to cast it
anyway after the call.

As you still have to cast the *result*, you actually would'nt even have to
supply the numeric type. You could try something simple like:

static decimal MyParse(String str)
{
return decimal.Parse(str);
}



// Bjorn A
 
S

Stefan Simek

Simply:

object MyFunc(Type T, String Str)
{
return Convert.ChangeType(Str, T);
}

The Convert.ChangeType() method tries to retrieve an IConvertible interface
for the first argument and then calls the respective conversion method.

HTH,
Stefan
 

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