Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of this code?

I'm reading through the source code for ASP.NET MVC3, and I came across the following inside of the code for ControllerBase:

public interface IController
{
    void Excecute(RequestContext requestContext);
}


public abstract class ControllerBase : IController
{

    protected virtual void Execute(RequestContext requestContext)
    {
        if (requestContext == null)
        {
            throw new ArgumentNullException("requestContext");
        }
        if (requestContext.HttpContext == null)
        {
            throw new ArgumentException(MvcResources.ControllerBase_CannotExecuteWithNullHttpContext, "requestContext");
        }

        VerifyExecuteCalledOnce();
        Initialize(requestContext);

        using (ScopeStorage.CreateTransientScope())
        {
            ExecuteCore();
        }
    }

    void IController.Execute(RequestContext requestContext)
    {
        Execute(requestContext);
    }
}

ControllerBase provides an implementation of Execute, but then it has something that provides a definition for.. IController.Execute?

Why is this done, and what does it achieve? It seems like it serves no purpose.

like image 835
Mike Bailey Avatar asked Apr 12 '12 21:04

Mike Bailey


1 Answers

This code makes it possible for you to override the Execute method.

Remember that a normally implemented interface method is public (and not virtual or abstract), so you can't override it in derived classes and creating a new Execute method wouldn't be accessible through the IController interface by default (without this interface to protected virtual technique). By creating a protected virtual method (which you call from the explicitly implemented interface method) allows derived classes to override the Execute method without breaking the interface implementation.

I found an excellent article about this here: C# Overriding Interface Methods in Subclasses

like image 146
BenSwayne Avatar answered Feb 08 '23 23:02

BenSwayne