0

sorry for the explanation but this is the best i can describe it, hopefully the code will help. (i've removed implementation from the classes and renamed to make it as bare bones as i can)

I get a cast exception as i convert my interface to interface below is the code. Is there anyway i can get this to work?

  var instance = new Service1() as IService<PocoClass1>; //this works
  var instance2 = new Service1() as IService<PocoBase>; // this fails but i want it to work


public abstract class PocoBase
{
    public int GetAll()
    {
        return 0;
    }
}

public class PocoClass1: PocoBase 
{
}


public interface IService<T> where T : PocoBase
{
    void Add(int x);
}

public class Service1 : IService<PocoClass1>
{
    public void Add(int x)
    {
    }
}
UndeadEmo
  • 433
  • 1
  • 6
  • 15
  • Your base class needs to implement the Interface. Please see this SO article (https://stackoverflow.com/questions/2705163/c-abstract-classes-need-to-implement-interfaces) – Ryan Wilson Jul 02 '18 at 15:15
  • does not work either, var instance3 = new Service1() as IService; //(in my main method) public interface IPocoBase { int GetAll(); } public abstract class PocoBase: IPocoBase { public int GetAll() { return 0; } } – UndeadEmo Jul 02 '18 at 15:36
  • the Covariance and contravariance real world example your provided, Based on that what i tried should work – UndeadEmo Jul 02 '18 at 15:39
  • this is the correct link finally found it https://stackoverflow.com/questions/44615138/c-sharp-casting-generic-child-type-to-parent, adding out to – UndeadEmo Jul 02 '18 at 15:49

0 Answers0