Can I Use Generics in Web Services?

By Ashish Khandelwal, July 25, 2010

Unfortunately, no. Web services have to expose a WSDL-based contract. Such contracts are always limited by the expressiveness of the message format being used. For example, HTTP-GET based web services only support primitive types such as int or string, but not complex types like a DataSet. SOAP-based web services are more capable, but SOAP has no ability to represent generic type parameters. As a result, at present, you cannot define web services that rely on generic types. That said, you can define .NET web services that rely on closed constructed generic types, for example:

public class MyWebService
{
   [WebMethod]
   public List<string> GetCities()
   {
      List<string> cities = new List<string>();
      cities.Add("New York");
      cities.Add("San Francisco");
      cities.Add("London");
      return cities;
   }
}

In the above example, List<string> will be marshaled as an array of strings.

VN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)

Leave a Reply