Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

How to constrait a generic class to work with just two classes

I have a generic class modeling a protocol that encapsulates other protocols. All the protocols implement a specific interface but this generic class must contain only one of two of these protocols as in the real world the other combinations do not exist.

Is there a way to specify the two allowed classes?

Currently I have:

public class ProtocolEncapsulator<TContainedCommand> : IBaseCommand where TContainedCommand : IBaseCommand 

But this allows users of the framework to create non-sense combinations.

Thanks

Upvotes: 0

Views: 148

Answers (1)

Brian S
Brian S

Reputation: 5785

I would suggest creating an interface that is implemented only by the two protocols and then use a type constraint to restrict the method in question.

Something like:

public interface IExclusiveCommand : IBaseCommand
{
    void ExclusiveMethod();  //Not necessary if there are no differences between Base and Exclusive
}

public class ProtocolEncapsulator<TContainedCommand> : IBaseCommand where TContainedCommand : IExclusiveCommand
{
}

While it does add another interface and might be viewed as adding complexity, I believe it actually simplifies things by making them more explicit and clear. And the compile-time restriction makes it more maintainable and easier to troubleshoot.

Upvotes: 2

Related Questions