65

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

is there any difference?

Artur Keyan
  • 7,643
  • 12
  • 52
  • 65

3 Answers3

81

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.

Bilaal Rashid
  • 828
  • 2
  • 13
  • 21
dknaack
  • 60,192
  • 27
  • 155
  • 202
16

When you return null from an action the MVC framework (actually the ControllerActionInvoker class) will internally create a new EmptyResult. So finally an instance of the EmptyResult class will be used in both cases. So there is no real difference.

In my personal opinion return new EmptyResult() is better because it communicates more clearly that your action returns nothing.

Philip Smith
  • 2,741
  • 25
  • 32
nemesv
  • 138,284
  • 16
  • 416
  • 359
8

Artur,

both do basically the same in that the http header is sent back along with a blank page. you could however, tweak that further if you wished and return a new HttpStatusCodeResult() with the appropriate statusCode and statusDescription. i.e.:

var result = new HttpStatusCodeResult(999, "this didn't work as planned");
return result;

I think that may be a useful alternative.

[edit] - found a nice implementation of HttpStatusCodeResult() which exemplifies how to leverage this with google etc in mind:

http://weblogs.asp.net/gunnarpeipman/archive/2010/07/28/asp-net-mvc-3-using-httpstatuscoderesult.aspx

jim tollan
  • 22,305
  • 4
  • 49
  • 63
  • I like your approach and I have to add that we can use some predefined code from here https://en.wikipedia.org/wiki/List_of_HTTP_status_codes – NoWar Jul 17 '15 at 16:57