.NET knows many ways to convert data types:
Convert
-class;(Try)Parse
and ToString
, etc.;IConvertable
;TypeConverter
;So if am converting one datatype to another, I need to know both types and I need to know which conversion method to use. And this becomes pretty nasty if one of those two types (or both) is a generic type.
So my question is: I there is uniform (generic) way in .NET to convert one data type to another, which might use all the other limited methods?
A good, generic way to convert between types is with Convert.ChangeType
. Here's an example of how you could use it to write a generic converting method:
public static TResult Convert<TResult>(IConvertible source)
{
return (TResult)System.Convert.ChangeType(source, typeof(TResult));
}
It, like other Convert
methods, internally calls the IConvertible
interface.
This will not make use of your other conversion options:
ToString
; for that, you could add a check to see if TResult
is string
and if so, (after appropriate null checks) simply call ToString
on your input.TypeConverterAttribute
(TypeDescriptor.GetConverter
seems to be the way to go from there)(Try)Parse
methods, (which you'd invoke), andop_Implicit
and op_Explicit
, which you'd likewise invoke)These are each fairly self-explanatory if you know a bit about reflection, but I could elaborate if any prove difficult.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With