Reputation: 12934
.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?
Upvotes: 5
Views: 721
Reputation: 45096
You imply those are all the same
They are not
Pick the appropriate
Convert Class
Converts a base data type to another base data type.
Parse is from string
ToString is a to string
IConvertible Interface
Defines methods that convert the value of the implementing reference or value type to a common language runtime type that has an equivalent value.
TypeConverter Class
Provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties.
Yes you need to know the type you are converting to.
And you should be aware if the type you are converting from.
With generics there is no built in.
At best you provide a method.
But why do you need to convert generics?
You seem to imply that more than one way is a bad thing.
For a single way then I like the answer from Tim S. +1
But that does not mean I would ever use it.
The are even more ways to get data from a SQL database.
Is that a bad thing?
Upvotes: 0
Reputation: 56556
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.
Upvotes: 2