I have the following two interfaces
public class IMessage
{
}
public interface IListener<TMessage> where TMessage : IMessage
{
void ProcessMessage(TMessage message);
}
I need a specific Listener To implement IListener<TMessage>
that takes a specific type of message
public class DeleteEmployeeMessage : IMessage
{
public int EmployeeId { get; set; }
}
Now I implement my Listener like so
public class DeleteEmployeeListener : IListener<DeleteEmployeeMessage>
{
public void ProcessMessage(DeleteEmployeeMessage)
{
// CODE HERE
}
}
Now I want to create an object of DeleteEmployeeListener
and cast it to generic interface type;
IListener<IMessage> listenerInterfaceObj;
DeleteEmployeeListener concreteMessageListener = new DeleteEmployeeListener();
listenerInterfaceObj = (IListener<IMessage>) concreteMessageListener; // this line crashes at runtime
I get the following runtime error
System.InvalidCastException: 'Unable to cast object of type 'DeleteEmployeeListener' to type 'IListener`1[IMessage]'.'
Why is that? Why can't I cast a Cat
to an Animal
?