views:

46

answers:

2

In ASP.Net MVC if I have a method on a controller that returns a View should that method be of type ViewResult or the more general ActionResult?

+2  A: 

A similar question was asked on the ASP.NET forums: http://forums.asp.net/t/1423519.aspx

Basically, it comes down to style -- in OOP, you try to return the most specific type that you can given the situation. You don't return object for every method that you have -- sometimes you return string, sometimes List, sometimes a custom class.

In the forum replies, someone quotes Stephen Walther from his book:

NOTE This action method specifically declares that it returns an instance of ViewResult. It would work just the same if instead the method return type was ActionResult (the base class for all action results). In fact, some ASP.NET MVC programmers declare all their action methods as returning a nonspecific ActionResult, even if they know for sure that it will always return one particular subclass. However, it's a well-established principle in object-oriented programming that methods should return the most specific type they can (as well as accepting the most general parameter types they can). Following this principle maximizes convenience and flexibility for code that calls your method, such as your unit tests.

So using the more specific ViewResult would be preferred, especially from a unit testing perspective.

David Hoerster
Thanks David! Looking forward to this week's user group.
Lee Warner
+1  A: 

A method is most useful when its parameters are as general as possible (e.g., IEnumerable<T> instead of an array) and its return value is as specific as possible (e.g., IList<T> instead of IEnumerable).

With the return value, however, it's still better to use interfaces or abstract types instead of concrete types (e.g., IList<T> instead of List<T>) which will give you some flexibility with changing the implementation or at least minimize coupling with calling code.

If you don't foresee changing the result to any other kind of ActionResult, you can make it return a ViewResult. If you don't foresee any callers taking advantage of the ViewResult in particular, it can be returned as an ActionResult but it doesn't really matter either way.

Mark Cidade