Alexey Romanov
Alexey Romanov

Reputation: 170723

How to make a .Net generic method behave differently for value types and reference types?

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?

Upvotes: 3

Views: 2438

Answers (4)

Kuno
Kuno

Reputation:

Why not let the compiler choose?

public static Result<T> ToResult<T>(this T arg) where T: class
{ return new ImplRef(arg); }

public static Result<T> ToResult<T>(this T arg) where T: struct
{ return new ImplVal(arg)

to be used like:

"hi".ToResult();
3.ToResult();

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1062705

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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500225

Do you actually use the constraints in ImplRef and ImplVal? If not (i.e. if it's just so you can behave differently) you could drop the constraints, make the methods private, and just call them appropriately from Generic - or possibly have:

public static Result<T> ImplRef(T arg) where T : class 
{
    return ImplRefImpl(arg);
}

private static Result<T> ImplRefImpl(T arg)
{
    // Real code
}

public static Result<T> ImplVal(T arg) where T : struct
{
    return ImplValImpl(arg);
}

private static Result<T> ImplValImpl(T arg)
{
    // Real code
}

You should consider what to do if T is a nullable type, by the way - it doesn't actually satisfy either the class or struct constraints.

By the way, another way of testing for T being a value type (which may be more efficient - not sure) is:

if (default(T) == null)

Note that this will "pass" for a nullable type, unlike your test of IsValueType, so the behaviour isn't identical.

Upvotes: 2

Stewart Johnson
Stewart Johnson

Reputation: 14449

Is there a reason you can't go with the two separate implementations (that possibly both use a third common implementation)?

Using typeof means you're doing RTTI which will make your app slower. Using the compiler (by using separate implementations for class and struct) will be much quicker, since all the decisions about types will be handled by the compiler during JIT compiling.

Upvotes: 0

Related Questions