I want to do something like this:
public static TResult MyCast<TSource, TResult>(TSource item)
{
return (TResult)item;
}
Without restrictions on TSource or TResult and avoiding unnecessary boxing if possible.
Edit: I want to stress out, that I want a simple casting of types, not elaborate type conversion here. It would be perfectly ok to fail at casting, say string to int.
Is there any sane way to do this using CLR 2.0?
Edit: this is a simplified version, so it’s pretty useless, yes.
But consider casting generic collections, such as this:
public static Dictionary<string, TResult> CastValues<TSource, TResult>(this Dictionary<string, TSource> dictionary)
After some discussions with my co-workers, it seems like there’s no simple way to implement such a feature (if at all possible), so I’m stuck with code bloat of several very simple methods for different situations (i.e. up- and downcast of reference types and casting of some value types) 🙁
Too bad I can’t use .NET 4.0 with all it’s dynamic et al goodness.
This is straightforward when
TSourceandTResultare both reference types.If one or the other are value types, how do you want it to work? Value types can’t inherit from each other, so it’s not a matter of doing an up- or down-cast. You might expect numeric conversions between, say,
intanddouble, but you’d have to code these yourself: .NET doesn’t treat them as typecasts. And conversion between, say,DateTimeandstringinvolves more intelligence (what format? which culture? etc.).If you’re just handling reference types then this method can be a one-liner. If you want to handle value types as well then you’ll need to write special case code for the various combinations.
Edit:
Convert.ChangeTypedoes a reasonable job at encapsulating the various conversions between value types. However you mentioned you’re keen not to introduce boxing:Convert.ChangeTypeisn’t generic and it takes anobject.