What is the argument against declaring protected-access members on interfaces? This, for example, is invalid:
public interface IOrange
{
public OrangePeel Peel { get; }
protected OrangePips Seeds { get; }
}
In this example, the interface IOrange
would guarantee that implementors at least provide an OrangePips
instance to their inheritors. If the implementor wanted to, they could expand the scope to full public
:
public class NavelOrange : IOrange
{
public OrangePeel Peel { get { return new OrangePeel(); } }
protected OrangePips Seeds { get { return null; } }
}
public class ValenciaOrange : IOrange
{
public OrangePeel Peel { get { return new OrangePeel(); } }
public OrangePips Seeds { get { return new OrangePips(6); } }
}
The intent of protected
members on interfaces is to provide a support contract for inheritors (sub-classes), for example:
public class SpecialNavelOrange : NavelOrange
{
...
// Having a seed value is useful to me.
OrangePips seeds = this.Seeds;
...
}
(Admittedly, this wouldn't work for struct
s)
I can't see much of a case for private
or internal
modifiers in interfaces, but supporting both public
and protected
modifiers seems perfectly reasonable.
I'm going to try explaining the utility of protected
members on interface
s by separating them from interface
s entirely:
Let's imagine a new C# keyword, support
, to enforce inheritor contracts, so that we declare things as follows:
public support IOrangeSupport
{
OrangePips Seeds { get; }
}
This would allows us to contract classes to provide protected members to their inheritors:
public class NavelOrange : IOrange, IOrangeSupport
{
public OrangePeel Peel { get { return new OrangePeel(); } }
protected OrangePips Seeds { get { return null; } }
}
This is not particularly useful, because classes would already imply this contract by providing the protected
members in the first place.
But then we could also do this:
public interface IOrange : IOrangeSupport
{
...
}
Thereby applying IOrangeSupport
to all classes which implement IOrange
and requiring them to provide particular protected
members - which is not something we can currently do.
See Question&Answers more detail:
os