Brad Irby
Brad Irby

Reputation: 2542

Constraint one generic parameter to be a subtype of the other

I am trying to create a passthrough method that will call Unity to register a type. This is the body of the method I am trying to create:

public static void RegisterType<T,U>()
{
    myContainer.RegisterType<T, U>();
}

the myContainer property is an IUnityContainer. When I try to build this, I get

The type 'U' cannot be used as type parameter 'TTo' in the generic type or method 'Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType(Microsoft.Practices.Unity.IUnityContainer, params Microsoft.Practices.Unity.InjectionMember[])'. There is no boxing conversion or type parameter conversion from 'U' to 'T'.

How can I tell the compiler that U does implement the interface T?

Upvotes: 1

Views: 1297

Answers (1)

zerkms
zerkms

Reputation: 254926

Will not this work:

public static void RegisterType<T,U>() where U : T
{
    myContainer.RegisterType<T, U>();
}

?

Upvotes: 7

Related Questions