-2

I have the following class file where all properties are defined as follows

public class DataDto
{
    public ImmutableList<string> Header;

    public ImmutableList<ImmutableList<string> Rows;
}

I would like to add values to the to both properties but I do not know how to do that. I am learning c# and would like to know how to do that. In my program.cs file I am doing the following but I get a Object reference not set to an instance of an object exception

        var mydata = new DataDto();

        var headerList = new List<string>();
        var rowList = new List<string>();
        headerList.Add("1");
        headerList.Add("2");
        headerList.Add("3");

        rowList.Add("4");
        rowList.Add("5");
        rowList.Add("6");

        mydata.Header.AddRange(headerList);
        
        foreach (var value in mydata.Header)
        {
            Console.WriteLine(value);
        }

I would also like to fill in the rows as well with the object.

Robert
  • 29
  • 6
  • You are saying you are learning so i need to ask you this, Is there a specific reason you are using `ImmutableList` over a simple `List` – Franck Nov 26 '20 at 19:20

1 Answers1

0

You need to instantiate Header and Rows properties in your DataDto class before you can actually add values to these lists.

Another thing to note is that when using ImmutableList the Add, Remove operations return a new list, hence the immutability.

You could change your code to something like:

var myData = new DataDto();

var headerList = new List<string>();
headerList.Add("1");
headerList.Add("2");
headerList.Add("3");

myData.Header = ImmutableList.CreateRange<string>(headerList);

If you need to add more headers later you could do:

myData.Header = myData.Header.Add("4");

For the rows you could do:

var rows = ImmutableList<ImmutableList<string>>.Empty;
// add a row
var row1data = ImmutableList.Create<string>(new [] {
    "a", "b", "c"
};
rows = rows.Add(row1data);
myData.Rows = rows;

If you just want to fix your crash you can change your DataDto class to:

public class DataDto
{
    public ImmutableList<string> Header = ImmutableList<string>.Empty;

    public ImmutableList<ImmutableList<string>> Rows = ImmutableList<ImmutableList<string>>.Empty;
}
Cheesebaron
  • 24,131
  • 15
  • 66
  • 118