IList<int> throws Null Reference Exception when adding values
-
12-12-2019 - |
Question
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>();
}
OTHER TIPS
You should initialize your list with actual object, for example in the constructor. Add this to your class:
public ClientModelData()
{
LocationIDs = new List<int>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow