I have a problem to cast to generic parent, this is my codes
public interface IEvent
{
}
public interface IEventHandler<TEvent> where TEvent : IEvent
{
Task Handle(TEvent evt);
}
public class PersonCreatedEvent : IEvent
{
public int Id { get; set; }
}
public class PersonCreatedEventHandler : IEventHandler<PersonCreatedEvent>
{
public async Task Handle(PersonCreatedEvent evt)
{
Console.WriteLine("done");
}
}
And my code for casting is this:
var handler = new PersonCreatedEventHandler();
// exception occurred on this line
var cast = (IEventHandler<IEvent>)handler;
But I got exception when I want to cast instance.
Unable to cast object of type 'TestProject.ClientApi.PersonCreatedEventHandler' to type 'TestProject.ClientApi.IEventHandler`1[ElearnoInstitute.Endpoint.ClientApi.IEvent]'.
Why I get this exception? and how can resolve this problem.