1

I've got classes and interfaces like bellow.

public interface IOffer
{
    ...
}

public class SomeOffer: IOffer
{
   ...
}   

public interface IOfferManager<T>
{
    ...
}

public class OfferManager<T> : IOfferManager<T> where T : IOffer
{
    ...
}

factory class:

public OfferManager<IOffer> CreateOfferManager(int offerType)
{
    switch (offerType)
    {
        case 0:
        {                    
            return _kernel.Get<IOfferManager<SomeOffer>>("SomeOffer");  
            //expected OfferManager<SomeOffer>;                  
        }

         ...

    }
}

Method CreateOfferManager(int offerType) return error -> Cannot implicitly convert type IOfferManager<SomeOffer> to OfferManager<IOffer>. An explicit conversion exists (are you missing a cast?)

And the question is why it gives me back an error if SomeOffer is IOffer? I can't resolve this problem. I've tried different type of returned value. Did I make a mistake in classes and interfaces construction? I have no idea why it doesn't work and how to do this differently. What is the best solution in this case?

  • 1
    See [this question](https://stackoverflow.com/questions/3445631/still-confused-about-covariance-and-contravariance-in-out). Nothing to do with Ninject - that part of your question is irrelevant – canton7 Oct 21 '19 at 12:16
  • 1
    The declaration of `CreateOfferManager` promises that it will return an offer manager that can manage any type of IOffer. But you are trying to return an offer manager that can only manage certain types of IOffer objects (they must be a descendant of SomeOffer). That is not type-compatible and that is why it breaks. You can get around this by making `IOfferManager` [covariant](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/). – John Wu Oct 22 '19 at 01:37
  • Thanks you both! what in case if my `IOfferManager` has `T GetOffer()` and `bool SetOffer(T offer)`? I splited it into two separate interfaces and now i can initialize two different object. I would like to create one object responsible for getting and setting an offer. Is it possible? I tried create another interface `IOfferManagerAccessible` which implements `IOfferManagerSetable` and `IOfferManagerGetable` but this also doesn't work when i am trying initialize `IOfferManagerAccessible`. – Przemysław Sapiecha Oct 22 '19 at 09:02

0 Answers0