-1

I have two classes. First class is "StoreList":

class StoreList
{
    public string Code { get; set; }
    public string Name { get; set; }
    public int StoreId { get; set; }
}

Second is DataList:

class DataList
{
    public List<StoreList> StoreListData { get; set; } //I don't know if this is correct
}

So I can use in code like this:

var liststoreIds = client.storeList(sessionId); //here I get data from API, all ok

var storeList = new DataList();

foreach (var stores in liststoreIds)
{
    storeList.StoreListData.Add(new StoreList
    {
         Code = stores.code,
         Name = stores.name,
         StoreId = stores.store_id
    });
}

In code I get error: "Object reference not set to an instance of an object." Where is a problem?

DaniKR
  • 1,986
  • 10
  • 31
  • 48

1 Answers1

2

You have to initialize the list, either in the constructor or inline:

class DataList
{
    public List<StoreList> StoreListData { get; set; } = new List<StoreList>();
}
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • Thank you very much, I didn't know that you can initialize like this. Now @macceltura don't mar question as possible duplicate. I whant to mark your question as solution, what do you recomend? – DaniKR Mar 23 '18 at 14:30