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.
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
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