Interface with a property that has an interface as its type; class specifies implementation of interface but is invalid

Apologies if this is duplicate, I imagine it is, but I haven’t been able to find anything. I’m probably searching for the wrong thing.

public interface IMyThingA {}
public class A : IMyThingA {}

interface IMyThingB {
    IMyThingA SomeThingA { get; set; }
}

public class B : IMyThingB {     // B does not implement interface member 'IMyThingA.SomeThingA'
    public A SomeThingA;
}

I expected, with the above code, that the class B would be able to use a class which implements the expected interface (IMyThingA), but clearly I am mistaken. Is there a way to have a pattern like this work?

  • 2

    Imagine you had public class OtherA : IMyThingA {} and tried the following: IMyThingB b = new B(); b.SomeThingA = new OtherA(); This should illustrate, why this doesn’t work.

    – 

You can do this with generics and a type constraint. For example:

public interface IMyThingA { }
public class A : IMyThingA { }

interface IMyThingB<T> where T : IMyThingA
{
    T SomeThingA { get; set; }
}

public class B : IMyThingB<A>
{     
    public A SomeThingA { get; set;}
}

Leave a Comment