Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrain type parameter of a method to the interfaces implemented by another type

The intention of the following is to only allow the call IRegistration<Foo>.As<IFoo> if Foo implements IFoo:

interface IRegistration<TImplementation>
{
   void As<TContract>() where TImplementation : TContract;
}

This is not allowed by the C# 3.0 compiler. I get the following error:

'SomeNamespace.IRegistration.As()' does not define type parameter 'TImplementation'

Is there some way around this, other than putting both type parameters in the method declaration?

This question is inspired by this other question about Autofac.

like image 999
Wim Coenen Avatar asked Jan 29 '26 10:01

Wim Coenen


1 Answers

You are trying to add a constraint on a type parameter that does not exist in the type parameter list.

Is this what you meant?

interface IRegistration<TImplementation> where TImplementation : TContract
{
   void As<TContract>();
}

Though this will not compile either - you can't have a generic constraint on a generic type.

This will compile, though will probably not produce the constraint you want on the method itself:

interface IRegistration<TImplementation,TContract> where TImplementation : TContract
{
   void As<TContract>();
}

See if this will do:

interface IRegistration<TImplementation,TContract> where TImplementation : TContract
{
   void As();
}

This way, any time you use TImplementation, it will be constrained to be a TContract and you can still use TContract in the As method.

You can find more information here - look at the section towards the end of the page, titled "Type Parameters as Constraints".

like image 166
Oded Avatar answered Feb 01 '26 02:02

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!