I have two implementations of a method, one for value types and another for reference types:
public static Result<T> ImplRef(T arg) where T : class {...} public static Result<T> ImplVal(T arg) where T : struct {...}
I want to write a method which calls the correct implementation like this
public static Result<T> Generic(T arg) { if (typeOf(T).IsValueType) return ImplVal(arg); else return ImplRef(arg); }
Obviously, the above implementation doesn’t compile. How can I do this with minimum of reflection?
The idea with generics is usually to do the same logic with whichever inputs you are given, although obviously you need to be practical. Personally, I’d probably use two different methods, rather than brute-force them into the same method, but that would make it hard to call from a generic method just knowing about
T. There is no way of satisfying the: class/: structfrom static code, although theMakeGenericMethodapproach might work, but will be an order of magnitude slower.(substitute
typeof(Program)with the type that hosts the methods)The alternative (as Jon notes) is to cache the (typed) delegate to the method:
More work, but will be plenty quick. The static constructor (or you could use a property/null check) ensures we only do the hard work once.