return new EmptyResult() VS return NULL

asp.net Mvcasp.net Mvc-3Action

asp.net Mvc Problem Overview


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

is there any difference?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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.

Solution 2 - asp.net Mvc

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.

Solution 3 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArtur KeyanView Question on Stackoverflow
Solution 1 - asp.net MvcdknaackView Answer on Stackoverflow
Solution 2 - asp.net MvcnemesvView Answer on Stackoverflow
Solution 3 - asp.net Mvcjim tollanView Answer on Stackoverflow