Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Convert Types at Runtime?

Tags:

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?

like image 623
Timothy Khouri Avatar asked Nov 23 '08 19:11

Timothy Khouri


People also ask

Which operator is used to converts the input to the specified .NET Framework type?

The Explicit operator, which defines the available narrowing conversions between types. For more information, see the Explicit Conversion with the Explicit Operator section. The IConvertible interface, which defines conversions to each of the base . NET data types.

How you will convert an object data type to a basic data type?

You convert an Object variable to another data type by using a conversion keyword such as CType Function.

What is type conversion explain its types?

In computer science, type conversion or typecasting refers to changing an entity of one datatype into another. There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting.


1 Answers

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); 
like image 77
Asher Avatar answered Oct 06 '22 14:10

Asher