return new EmptyResult() VS return NULL

Artur Keyan picture Artur Keyan · Dec 19, 2011 · Viewed 49.7k times · Source

in ASP.NET MVC when my action will not return anything I use return new EmptyResult() or return null

is there any difference?

Answer

dknaack picture dknaack · Dec 19, 2011

You can return null. MVC will detect that and return an EmptyResult.

MSDN: EmptyResult represents a result that doesn't do anything, like a controller action returning null

Source code of MVC.

public class EmptyResult : ActionResult {

    private static readonly EmptyResult _singleton = new EmptyResult();

    internal static EmptyResult Instance {
        get {
            return _singleton;
        }
    }

    public override void ExecuteResult(ControllerContext context) {
    }
}

And the source from ControllerActionInvoker which shows if you return null, MVC will return EmptyResult.

protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) {
    if (actionReturnValue == null) {
        return new EmptyResult();
    }

    ActionResult actionResult = (actionReturnValue as ActionResult) ??
        new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };
    return actionResult;
}

You can download the source code of the Asp.Net MVC Project on Codeplex.