views:

89

answers:

2

Since there is no implicit conversion between Mvc.JsonResult and Mvc.ViewResult I cannot just utilize a conditional operator but instead end up with a cast.

Which leads me to my question is the performance hit I will take for boxing the JsonResult worth it or should I just do a normal if...else block?

The code below appears inside a normal controller action: public ActionResult Inactivate()

No Boxing

if (Request.IsAjaxRequest())
{
    return Json(foo);
}
else
{
    return View(bar);
}

VS Boxing

return Request.IsAjaxRequest() ? (ActionResult)Json(foo) : View(bar);
A: 

I think JsonResult and ViewResult both inherit from ActionResult, so no casting is necessary. In your "No Boxing" code block, you need the keyword return in from of Json and View.

Josh Pearce
I would have thought so but I get a compiler error if don't cast `Json` to `ActionResult`
ahsteele
+2  A: 

You can do whichever works better for you. There should be no performance impact, so it's just a matter of coding style and clarity.

In your second example, you need to cast either the Json(foo) or the View(bar). This is because the ?: operator needs to know the type of its arguments, and it's not smart enough to figure out the common base type. That's strictly a compile-time thing and it has no effect on performance.

Also, there's no boxing happening here. JsonResult and ViewResult are both classes, not structs, so they are both already on the heap.

Even if there were boxing, I doubt it would have any real impact on performance. ASP.NET MVC is doing reflection behind the scenes, and that's way more expensive than boxing.

Richard Beier
I learned several things from your answer. Thank you.
ahsteele