Search code examples
c#collectionsilisticollection

IList<int> throws Null Reference Exception when adding values


I have a class:

public class ClientModelData
{
    public int clientID { get; set; }
    public IList<int> LocationIDs { get; set; }
}

When I call it:

ClientModelData obj = new ClientModelData();
obj.LocationIDs.Add(1);

It throws an exception:

`((System.Collections.Generic.ICollection<int>)(client.LocationID))' is null`

Solution

  • LocationIDs is not initialized therefore it is giving you the error.

    public IList<int> LocationIDs { get; set; }
    

    You should create an instance in the constructor

    public ClientModelData()
    {
      LocationIDs = new List<int>();
    }