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
/ : struct
from static code, although the MakeGenericMethod
approach might work, but will be an order of magnitude slower.
// slow; use with caution
public static Result<T> Generic<T>(T arg) {
if (typeof(T).IsValueType)
return (Result<T>)typeof(Program).GetMethod("ImplVal")
.MakeGenericMethod(typeof(T))
.Invoke(null, new object[] {arg});
else
return (Result<T>)typeof(Program).GetMethod("ImplRef")
.MakeGenericMethod(typeof(T))
.Invoke(null, new object[] { arg });
}
(substitute typeof(Program)
with the type that hosts the methods)
The alternative (as Jon notes) is to cache the (typed) delegate to the method:
public static Result<T> Generic<T>(T arg) {
return Cache<T>.CachedDelegate(arg);
}
internal static class Cache<T>
{
public static readonly Func<T, Result<T>> CachedDelegate;
static Cache()
{
MethodInfo method;
if (typeof(T).IsValueType)
method = typeof(Program).GetMethod("ImplVal")
.MakeGenericMethod(typeof(T));
else
method = typeof(Program).GetMethod("ImplRef")
.MakeGenericMethod(typeof(T));
CachedDelegate = (Func<T, Result<T>>)Delegate.CreateDelegate(
typeof(Func<T, Result<T>>), 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.