0
interface IMyEvent { }

class SpecificEvent : IMyEvent {  }

interface IMySubscriber<TEvent> where TEvent : IMyEvent { }

class MySubscriber<TEvent> : IMySubscriber<TEvent> where TEvent: IMyEvent { }

class EventPublisher
{
    public void Subscribe(IMySubscriber<IMyEvent> subscriber)
    {

    }
}

I can't understand why it's impossible to execute Subscribe method with a MySubscriber<SpecificEvent> object.

new EventPublisher().Subscribe(new MySubscriber<SpecificEvent>());

It says that it can't cast MySubscriber<SpecificEvent> to IMySubscriber<IMyEvent>. Could you please explain why it happens or provide some links where I can read about it.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
E. Shcherbo
  • 1,128
  • 8
  • 15

1 Answers1

2

For this to work you must mark the interface with an out generic parameter:

interface IMySubscriber<out TEvent> where TEvent : IMyEvent { }

http://rextester.com/FAXW57974

See: still confused about covariance and contravariance & in/out

Jamiec
  • 133,658
  • 13
  • 134
  • 193