nickwesselman
nickwesselman

Reputation: 6890

Implementing interface with generic type that is less constrained than that of a method I need to call

I'm implementing an interface in order to inject custom business logic into a framework that utilizes Microsoft Unity. My core issue is that a the interface I need to implement defines the following method:

T InterfaceMethod<T>();

T has no constraints. In my code, I need to call a method from a different 3rd party library, with a method signature of

T AnotherMethod<T>() where T: class;

The type T is significant to the logic of AnotherMethod. Is there any way to call AnotherMethod<T>() within my implementation, without using reflection? I obviously need to take alternate action if T is a value type. Is there perhaps a way to autobox to work around this?

Upvotes: 6

Views: 171

Answers (3)

d--b
d--b

Reputation: 5779

What the others are saying is that you can go through object like this:

public interface ITest
{
    T InterfaceMethod<T>(T arg);
}

public interface IAnotherTest
{
    U AnotherMethod<U>(U arg) where U : class;
}

public class Test : ITest
{
    private IAnotherTest _ianothertest;

    public T InterfaceMethod<T>(T arg)
    {
        object argU = arg as object;
        if (argU != null)
        {
            object resultU = _ianothertest.AnotherMethod(argU);
            T resultT = (T)Convert.ChangeType(resultU, typeof(T));
            return resultT;
        }
        return default(T);
    }
}

Upvotes: 0

d--b
d--b

Reputation: 5779

I am not sure this is exactly what you need, but this allows you to call AnotherMethod from InterfaceMethod without using reflection. It still uses a Convert.ChangeType though.

The idea is to make the implementation of the class generic with a constrain (here Tin). Then you convert the unconstrained type T of the InterfaceMethod to Tin. Finally you can call the AnotherMethod with the constrained type. The following works fine with strings.

public interface ITest
{
    T InterfaceMethod<T> (T arg);
}

public interface ITest2
{
    U AnotherMethod<U>(U arg) where U : class;
}

public class Test<Tin> : ITest, ITest2 where Tin : class
{
    public T InterfaceMethod<T> (T arg)
    {
        Tin argU = arg as Tin;
        if (argU != null)
        {
            Tin resultU = AnotherMethod(argU);
            T resultT = (T)Convert.ChangeType(resultU,typeof(T));
            return resultT;
        }
        return default(T);
    }

    public U AnotherMethod<U> (U arg) where U : class { return arg; }
}

Upvotes: 2

Tim S.
Tim S.

Reputation: 56576

I don't think that what you're looking for is possible without reflection. At best, you could just call AnotherMethod<object>() and cast the result. But this would only really work right if AnotherMethod's T isn't important for your purposes.

Upvotes: 1

Related Questions