Search code examples
c#contravariance

contravariance in generics - what for in that case


I dont know what for it is "in" TCommand keyword in that interface where TCommand is a class with a few properies needed for handler. Is it needed? What it gives in that context ? or maybe "in" is only explicit way to say what is implicit mechanism in generics ?

public interface ICommandHandler<in TCommand> where TCommand : class, ICommand
{
    Task HandleAsync(TCommand command);
}

Comment So ..it is related only for that specificCommandHandler = handler; where SpecificHandler variable can be assigned BaseHandler type ?

Additionally SpecificHandler can be used with a ... BaseCommand ?? like

specificHandler<SpecificCommand> sHandler = new SpecificHandler();
sHandler(BaseCommand) ;

?? if yes ... tell me what for ?:)


Solution

  • Suppose you have BaseCommand and SpecificCommand, where SpecificCommand : BaseCommand. With the contravariance you've specified, you could write:

    ICommandHandler<BaseCommand> handler = ...; // Whatever initialization you want
    // Implicit reference conversion
    ICommandHandler<SpecificCommand> specificCommandHandler = handler;
    

    Without the contravariance, that second statement wouldn't be valid, because there wouldn't be any implicit conversion from ICommandHandler<BaseCommand> to ICommandHandler<SpecificCommand>.

    Now you don't need that if all you want is to write handler.HandleAsync(new SpecificCommand()) - but if you want to pass a handler to a method expecting an ICommandHandler<SpecificCommand> then that implicit conversion is exactly what you want.