I have a class with a data model and I try to add data items into it.
When I add the items like following it is working:
class DataItem
{
public int Day { get; set; }
public double Value { get; set; }
}
DataItem[] value2023 = new DataItem[] {
new DataItem
{
Day = 1,
Value = 10
},
new DataItem
{
Day = 2,
Value = 20
},
new DataItem
{
Day = 3,
Value = 30
}
};
When I add the items like following it is not working.Because the data collection is empty I get System.NullReferenceException when I try to reach the elements of the data collection. (Method FillData is called initialy)
class DataItem
{
public int Day { get; set; }
public double Value { get; set; }
}
public void FillData()
{
DataItem[] value2023 = new DataItem[5];
for (int i=0; i<5;i++)
{
value2023.Append(new DataItem { Day = i+1, Value = i*10});
}
}
What could be the problem? If .Append is the wrong command, how else can I add items programmatically to my data collection?
1