I've been trying to work out how to get an equivalent of the following Java code in C# (Command is a functional interface).
public interface Executor<C extends Command> {
void execute(final C command) throws Exception;
}
The way my code is currently designed in the Java version, it is necessary for the type C to extend Command, which by my understanding is handled with covariance in C#.
However according to the C# docs, something like the following won't work because "The type is used only as a return type of interface methods and not used as a type of method arguments"
interface IExecutor<out Command>
{
void Execute(Command command);
}
Is there a way of specifiying that the type of the parameter for a method must be the covariant to the type of the interface in C#?
I'm relatively new to C#, so it could be that this is an XY problem, but I haven't found a solution that would work so far.
interface IExecutor<T> where T : Command { void Execute(T command); }? Although in your example, you can just dointerface IExecutor { void Execute(Command command); }(note that this isn't covariance. Interface covariance lets you writeIEnumerable<object> x = new List<string>(), which is something a bit different) - canton7wherestatement? - J LewisIEnumerableis declared asIEnumerable<out T> { ... }, which lets you write e.g.IEnumerable<object> x = new List<string>()- i.e. it tells the compiler that it's safe to refer to aList<string>as a collection of any old objects, because you can only ever take items out of the collection, and not put them in. - canton7