Question

My scenario should be simple... the type I want to convert FROM is ALWAYS 'string'. What I want to convert to... could be many things - ints, DateTimes, ... strings, etc.

This would be easy:

string valueToConvertFrom = "123";

int blah = Convert.ToInt32(valueToConvertFrom);

However... I don't know (until runtime) that the value I need to convert to is an 'Int' (or whatever). I have tried this:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

object blah = Convert.ChangeType(valueToConvertFrom, convertToType);

But that gives me the following error: "Object must implement IConvertible."

I don't want to have to do a switch statement and call "Convert.ToBlah" based on the type name... any suggestions?

Was it helpful?

Solution

the clean way to do it is using the a TypeConverter. you can get an instance of a type converter by calling the TypeDescriptor.GetConverter and then using the instance of the type converter to do the convertion. so something like this:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

TypeConverter tc =  TypeDescriptor.GetConverter(convertToType);             

object blah =tc.ConvertFromString(valueToConvertFrom);

OTHER TIPS

String class implements IConvertible, this code simply SHOULD work. Which version of .NET are you aiming?

object o = Convert.ChangeType( str, convertToType );

Besides, most of the types you mentioned implement Parse method, so your best shot might be something like this.

Type convertToType = ...;
MethodInfo mi = convertToType.GetMethod("Parse", BindingFlags.Static);
object blah;
if(mi != null)
{
    blah = mi.Invoke(null, new object[]{valueToConvertFrom});
}
else
{
    // the type doesn't implement the Parse method, handle it another way :/
}

Timothy's question, as applied generally to the question of Type conversion in .NET, is a very big issue. While conversion strategies are somewhat straightforward in specific scenarios with known types, unfortunately there is no generalized strategy in any implementation of .NET to accomplish Type conversion at run-time from one arbitrary Type to another, nor is such a strategy forthcoming from Redmond. However, Microsoft supplies some good guidelines for the general concept of Type conversion, including:

I have had to deal with the same general issue in my systems, and as a solution I have consolidated all the standard strategies into one method. The scope of this issue is broad and the related conversion strategies are varied, so this consolidated approach can only be covered in a complete technical article. However, I offer here a copy of my method documentation in hopes this will help you get a firm grasp on the overall requirements you will need to address if you want to develop a similar, generalized solution. Here's the link to my documentation:

I hope this helps you out,

Mark

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top