Search code examples
c#genericstype-constraints

Generic type constraint on generic type


I have a class like this:

public class Proxy<TClient>()
    where TClient : ClientBase<TChannel>
{

}

I want to be able to specify something like this:

where TClient : ClientBase<TChannel>
where TChannel : class

but without specifying it in the class definition like so:

public class Proxy<TClient, TChannel>()

Is there a way to do this or am I required to have the second type definition as above?


Solution

  • That's not possible. You have to include TChannel as a generic type parameter of Proxy.

    One of the options to get over this “limitation” (in quotes because it is a by-design feature that arises from how the C# type system works) is to use an interface which each channel would be supposed to implement:

    public interface IChannel { … }
    
    public class Proxy<TClient>()
        where TClient : ClientBase<IChannel>
    { 
    }
    
    public class MyObscureChannel : IChannel { … }
    
    public class MyObscureClient : ChannelBase<MyObscureChannel> { … }
    
    …
    
    var client = new Proxy<MyObscureClient>(…); // MyObscureChannel is implied here