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?
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;}
}
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.