IList<int> throws Null Reference Exception when adding values

混江龙づ霸主 提交于 2020-01-07 01:59:13

问题


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`

回答1:


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>();
}



回答2:


You should initialize your list with actual object, for example in the constructor. Add this to your class:

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


来源:https://stackoverflow.com/questions/12684954/ilistint-throws-null-reference-exception-when-adding-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!