Warcaith
Warcaith
CC#
Created by Warcaith on 4/15/2024 in #help
Issue with generic interfaces (covariance/contravariance)
Hello! Currently, I have these interfaces within my project:
c#
public interface IResult<out TResponse>
{
public bool Success { get; }
public TResponse? Response { get; }
}

public interface ICommand<in TOptions, out TResponse>
{
IResult<TResponse?> Execute(TOptions options);
}

public interface ICommand<in TOptions>
{
IResult<object?> Execute(TOptions options);
}

public interface ICommand
{
IResult<object?> Execute(object options);
}

public class CommandOptions
{

}

public class Command : ICommand<CommandOptions>
{
public IResult<object?> Execute(CommandOptions options)
{
}
}
c#
public interface IResult<out TResponse>
{
public bool Success { get; }
public TResponse? Response { get; }
}

public interface ICommand<in TOptions, out TResponse>
{
IResult<TResponse?> Execute(TOptions options);
}

public interface ICommand<in TOptions>
{
IResult<object?> Execute(TOptions options);
}

public interface ICommand
{
IResult<object?> Execute(object options);
}

public class CommandOptions
{

}

public class Command : ICommand<CommandOptions>
{
public IResult<object?> Execute(CommandOptions options)
{
}
}
However, I'm unable to create a command like this:
c#
object options = new CommandOptions();
ICommand<object> command = new Command();
command.Execute(options);
c#
object options = new CommandOptions();
ICommand<object> command = new Command();
command.Execute(options);
Cannot implicitly convert type 'Command' to 'ICommand<object>'. An explicit conversion exists (are you missing a cast?)
Cannot implicitly convert type 'Command' to 'ICommand<object>'. An explicit conversion exists (are you missing a cast?)
... which makes it impossible for me to create a command and options dynamically. I have probably a design issue within my interfaces, so please, if there's anything that should be changed, don't hesitate to make these changes. Thanks! 😁 (Downcasting to ICommand<object> gives me an System.InvalidCastException)
22 replies