I just stumbled across IController
and noticed that it has a method Execute
. My question is that given that Controller
derives from ControllerBase
which implements the interface IController
, how is it that ControllerBase
can implement Execute
as protected virtual
?
My understanding is that an interface must be implemented as a public method. My understanding of this is further complicated as you can't call Execute
on an instantiated Controller
and you must instead cast it to an instance of IController
.
How is it possible to have an interface implemented as a protected method?
To add a bit more, I know about explicit interface implementation, however if you view the source code for ControllerBase
at you will see that the method is implemented as protected virtual void Execute(RequestContext requestContext)
It's called explicit Interface Implementation.
A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.
Read more on MSDN: Explicit Interface Implementation Tutorial.
Simple sample:
interface IControl
{
void Paint();
}
public class SampleClass : IControl
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
protected void Paint()
{
// you can declare that one, because IControl.Paint is already fulfilled.
}
}
And usage:
var instance = new SampleClass();
// can't do that:
// instance.Paint();
// but can do that:
((IControl)instance).Paint();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With