Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniform method to convert data types

.NET knows many ways to convert data types:

  • Convert-class;
  • Functions inside a type like (Try)Parse and ToString, etc.;
  • Implementation of interface IConvertable;
  • The TypeConverter;
  • The implicit and explicit conversion operator;
  • Am I missing another one?

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?

like image 629
Martin Mulder Avatar asked Nov 02 '22 22:11

Martin Mulder


1 Answers

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:

  • The most common I'd think would be 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.
  • Using reflection you could check for:
    • the TypeConverterAttribute (TypeDescriptor.GetConverter seems to be the way to go from there)
    • (Try)Parse methods, (which you'd invoke), and
    • implicit/explicit conversion operators (the methods op_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.

like image 127
Tim S. Avatar answered Nov 08 '22 10:11

Tim S.