C# – Should web service response use a base class or generic class

cjsonrestwcfweb services

In my RESTful WCF web service I have something like the following response object.

public class WebResponse<T>
{ 
        public bool Success { get; set; }
        public T Data { get; set; }    
        public string ErrorMessage { get; set; }
}    

This way I can capture any errors that occur during the request to the web service. It also separates the data object from the response object. Another way this could be done is with a response base class like this.

public abstract class WebResponseBase
{
        public bool Success { get; set; }
        public string ErrorMessage { get; set; }
}

public class CarResponse : WebResponseBase
{
        public string Manufacturer { get; set; }
        public string Make { get; set; }
}

I personally prefer the first method as it gives me a clear separation of the data and the response/error status and allows me to easily return lists/arrays etc. without having to create multiple classes.

Are there any benefits to using the base class? Are there any limitations to using the generic class?

Best Answer

The generic response looks effectively clearer, but requires slightly more typing. For example, instead of:

var response = this.GetCar();
if (respose.Success)
{
    Debug.WriteLine(response.Manufacturer);
}

the caller has to write:

var response = this.GetCar();
if (respose.Success && response.Data != null)
{
    Debug.WriteLine(response.Data.Manufacturer);
}

Still, I personally would prefer using generics, since:

  1. It makes it easy to understand what belongs to the protocol, and what is the actual data,

  2. It allows extending or modifying the protocol without carrying for collisions.

    Imagine car has Size property. Later, WebResponse should implement Size property to specify the size of the response. Now you have a problem with Car. If data is dynamic, you can't even use your IDE to discover the collisions, and the compiler won't warn you neither.

Also note that according to MSDN, you wouldn't be able to use generics if you want the objects to traverse the boundaries of a context (like in a situation of a sandbox):

The current version of the common language runtime does not support generic ContextBoundObject types or nongeneric ContextBoundObject types that have generic methods.