ASMX 2.0 - Nullable Types

less than 1 minute read

ASP.NET Web Services (ASMX) in .NET 2.0 introduces support for nullable types. In .NET 1.0 and 1.1, the framework didn’t support xsi:nil for value types because, as we know, value types can’t be set to null. This commonly caused interop problems, particularly with J2EE applications.

The following simple web service shows how a method with a nullable parameter.

<%@ WebService Language="C#" Class="SimpleService" %>

using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace="urn:simple")]
public class SimpleService {

    [WebMethod]
    public string TestNullable(int? value) {
        if(value.HasValue) {
            return "The number is " + value.ToString();
        } else {
            return "The number was not supplied.";
        }
    }
}

This produces the following WSDL fragment:

<s:element name="TestNullable">
  <s:complexType>
    <s:sequence>
      <s:element minOccurs="1" maxOccurs="1" name="value" <span style="background-color:yellow">nillable="true"</span> type="s:int" /> 
    </s:sequence>
  </s:complexType>
</s:element>

The nillable attribute indicates that it is valid for the element to be empty. In that case, the service will set value to null.

Updated: