0

I have the following classes (some of them are in the PRISM framework and cannot be changed):

public abstract class NetworkEventBase<T> : CompositePresentationEvent<T> where T : NetworkEventPayload { }
public class NetworkEventPayload { }
public class TestEvent : NetworkEventBase<TestPayload> { }
public class TestPayload : NetworkEventPayload { }

// the following classes are PRISM classes:
public class CompositePresentationEvent<TPayload> : EventBase { }
public abstract class EventBase { }

Now I need to convert an instance of TestEvent to its base class NetworkEventBase inside a decorator for IEventAggregator. IEventAggregator looks like:

public interface IEventAggregator
{
    TEventType GetEvent<TEventType>() where TEventType : EventBase, new();
}

Now in my decorator I try to convert like this:

public class MessageBusAdapterInjectorDecorator : IEventAggregator {
    ...

    public TEventType GetEvent<TEventType>() where TEventType : EventBase, new()
    {
        var aggregatedEvent = this.eventAggregator.GetEvent<TEventType>();
        var networkEvent = aggregatedEvent as NetworkEventBase<NetworkEventPayload>;

        if (networkEvent != null)
        {
            networkEvent.MessageBusAdapter = this.messageBusAdapter;
        }

        return aggregatedEvent;
    }
}

However, networkEvent is always null, even when the runtime type of aggregatedEvent is TestEvent.

cguedel
  • 1,092
  • 1
  • 14
  • 28

1 Answers1

1

You seem to hope that the class called NetworkEventBase<T> would be covariant in T. But generic classes can't be covariant in C# (generic interfaces can).

See other threads on this issue.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • Thanks, I have now created an interface that defines a method to inject the IMessageBusAdapter into the event. – cguedel Jul 18 '13 at 08:23