Reputation: 26930
interface IAlpha
{
IBeta BetaProperty { get; set; }
}
interface IBeta
{
}
class Alpha : IAlpha
{
public Beta BetaProperty { get; set; } // error here
}
class Beta : IBeta
{
}
'InterfaceTest.Alpha' does not implement interface member 'InterfaceTest.IAlpha.BetaProperty'. 'InterfaceTest.Alpha.BetaProperty' cannot implement 'InterfaceTest.IAlpha.BetaProperty' because it does not have the matching return type of 'InterfaceTest.IBeta'.
My question is why is a property implementation restricted to the very same type. Why can't I use the derived type instead?
Upvotes: 5
Views: 5506
Reputation: 1499660
You have to implement the exact same interface. For example, this should be valid:
IAlpha alpha = new Alpha();
alpha.BetaProperty = new SomeOtherIBetaImplementation();
... but that wouldn't work with your code which always expects it to be a Beta
, would it?
You can use generics for this though:
interface IAlpha<TBeta> where TBeta : IBeta
{
TBeta BetaProperty { get; set; }
}
...
public class Alpha : IAlpha<Beta>
Of course, that may be overkill - you may be better just using a property of type IBeta
in Alpha
, exactly as per the interface. It depends on the context.
Upvotes: 11
Reputation: 49221
An interface declares a set of methods the class will have, so anyone using that interface knows what to expect.
So, if you're implementing that interface, you must implement the exact interface, so all the other users get what they expected.
Upvotes: 2