Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method to cast one arbitrary type to another in c#

Tags:

c#

generics

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.

like image 843
13xforever Avatar asked Sep 02 '25 14:09

13xforever


1 Answers

How would
x = MyCast<SourceType, ResultType>(y)
be any more useful than
x = (ResultType)y ?

like image 96
Henk Holterman Avatar answered Sep 05 '25 16:09

Henk Holterman