Roman Koliada
Roman Koliada

Reputation: 5082

Unable to cast generic type to interface

I have those types:

public interface ICommand {}

public class RemoveCommand<T>: ICommand
{
    public int Id {get; set;}
}

public interface ICommandHandler<TCommand> where TCommand: ICommand
{
    void HandleCommand(TCommand command);
}

public class RemoveCommandHandler<T> : ICommandHandler<RemoveCommand<T>>
{
   public void HandleCommand(SoftRemoveCommand<T> command)
   {
       ...
   }
}

While I was trying to resolve my ICommandHandler using Castle Windsor I received a cast exceptions. So I wrote this:

var obj = new RemoveCommandHandler<RemoveCommand<MyClass>>();
bool t1 = obj is ICommandHandler<RemoveCommand<MyClass>>; //return false!
bool t2 = obj.GetType().IsAssignableFrom(ICommandHandler<RemoveCommand<MyClass>>); //also false!

So my question is: Why my RemoveCommandHandler is not assignable from ICommandHandler?

Upvotes: 2

Views: 621

Answers (1)

dotnetom
dotnetom

Reputation: 24901

Your generic class declaration isRemoveCommandHandler<T>. So If you have class RemoveCommandHandler<RemoveCommand<MyClass>>, this means that your T is RemoveCommand<MyClass>.

So you should change RemoveCommandHandler<RemoveCommand<MyClass>> to RemoveCommandHandler<MyClass> and the code should work:

var obj = new RemoveCommandHandler<MyClass>();
bool t1 = obj is ICommandHandler<RemoveCommand<MyClass>>;  // returns true

Although for second check you need to switch sides:

bool t2 = typeof(ICommandHandler<RemoveCommand<MyClass>>).IsAssignableFrom(obj.GetType());  // returns true

Upvotes: 4

Related Questions