How do I convert from string to Type?

  • Thread starter Thread starter Ken Varn
  • Start date Start date
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
-----------------------------------
 
...
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
 
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
 
Back
Top