N Smith N Smith - 2 months ago 10
C# Question

sending Null to a List of Objects in a web service

I have a web service as per the below ;

[Route("/MyService", Verbs = "POST")]
public class MyData
{
public string GUID { get; set; }
public BankDetails BankDetail { get; set; }
public ContactNameData ContactNames { get; set; }
public List<AddressData> Addresses { get; set; }
}

public class AddressData
{
public string address1 { get; set; }
public string address2 { get; set; }
public string address3 { get; set; }
public string postalCode { get; set; }
public string city { get; set; }
public string state { get; set; }
public string countryCode { get; set; }
}

public class ContactNameData
{
public string title { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
}

public class BankDetails
{
public string sortCode { get; set; }
public string accountNumber { get; set; }
}

public class My_ServiceStack : Service
{

[Authenticate]
public object Post(MyData data)
{
// do something here
}
}


the problem I have is when I need to leave off the List of Addresses. Sending through a null value for the BankDetails object and the ContactNameData object works as expected but sending through a null value for the List gives me a NullExceptionError

How can I fix this so that I can send through a null to the List?

Answer

It is difficult to say what is happening without seeing the concrete line where the exception is thrown.

My best guess is that you do something with the list which is not allowed with null. A NullExceptionError does not exist in C# (except you defined such an Error for yourself), so I assume you mean a NullReferenceException. This exception is thrown when you dereference a null object reference. For example, Addresses.Count will throw such an exception because Count can not be used on a non-existing object.

There are several ways to fix such problems; the most common is to check for null before working with the list. Instead of

int addressCount;
addressCount = Addresses.Count;

you would simply write

int addressCount = 0;
if (Addresses != null)
     addressCount = Addresses.Count;

For more concrete information, I would have to see what you do with the list that causes the NullReferenceException.

Comments