0

Experts, what is wrong here:

I have these interfaces:

public interface IEvent {}

public interface ISingleEventModelChangeInterrogator<in TEvent> where TEvent : IEvent
{
    List<string> GetChangedCandidates(object context, TEvent changedEventArgs);
    bool IsInterestedIn(TEvent changedEventType);
}

Then, I have this base class:

public abstract class SingleEventModelChangeInterrogator<TEvent> : ISingleEventModelChangeInterrogator<TEvent>
        where TEvent : IEvent
    {
        public abstract List<string> GetChangedCandidates(object context, TEvent changedEventArgs);

        public bool IsInterestedIn(TEvent changedEventType)
        {
            return changedEventType.GetType() == typeof(TEvent);
        }
    }

And the following implementations:

    public class PriceChangeEvent : IEvent { }

    public class PurchaseOrderAffectedByPriceChangeInterrogator : SingleEventModelChangeInterrogator<PriceChangeEvent >
    {
        public override List<string> GetChangedCandidates(object context, PriceChangeEvent changedEventArgs)
        {
            throw new System.NotImplementedException();
        }
    }

When I attempt to add an instance of PurchaseOrderAffectedByPriceChangeInterrogator to a list of ISingleEventModelChangeInterrogator<IEvent>, as shown below:

 public class RetailEventCoordinator
    {
        public void Initialize()
        {
            var interrogators = new List<ISingleEventModelChangeInterrogator<IEvent>>();
            interrogators.Add(new PurchaseOrderAffectedByPriceChangeInterrogator());
        }
    }

I get the following error:

cannot convert 'model.materialization.service.interrogators.PurchaseOrderAffectedByPriceChangeInterrogator' to 'model.materialization.service.interrogators.ISingleEventModelChangeInterrogator<dotnet.model.materialization.service.events.IEvent>

What am I missing here?

Klaus Nji
  • 18,107
  • 29
  • 105
  • 185
  • 2
    It would have worked if it were `out TEvent`, but obviously `TEvent` can't be declared `out`. The assignment you want to do simply doesn't make sense. `PurchaseOrderAffectedByPriceChangeInterrogator` is a consumer of `PriceChangeEvent`. `ISingleEventModelChangeInterrogator` is a consumer of `IEvent`. A consumer of something more general (`IEvent`) IS A KIND OF consumer of something more specific (`PriceChangeEvent`), not the other way around. – Sweeper Jul 08 '20 at 01:17
  • 1
    See [the amazing picture in this answer](https://stackoverflow.com/a/19739576/5133585). – Sweeper Jul 08 '20 at 01:17
  • And I am here thinking I have a good handle on generics :) – Klaus Nji Jul 08 '20 at 01:55

0 Answers0