Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to have an interface implemented as a protected method?

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)

like image 372
Sam Avatar asked Mar 21 '23 19:03

Sam


1 Answers

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();
like image 65
MarcinJuraszek Avatar answered Apr 06 '23 20:04

MarcinJuraszek