0

I have problem with adding a record to list, which is a parametr of object 'TranchesDt'.

public class TranchesDt
{
    public List<startup> tranches {get; set;}
    public List<reservation> reservations { get; set; }
    public List<location> locations { get; set; }
}

There is the code, where I add objects to 'TranchesDt':

public static TranchesDt Parse(string filePath)
{
    string[] lines = File.ReadAllLines(filePath);
    TranchesDt dt = new TranchesDt();

    for (int i = 0; i < lines.Length; i++)
    {
        string recordId = lines[i].Substring(0, 2);

        switch (recordId)
        {
            case "11":
                {
                    dt.tranches.Add(Parse11(lines[i]));
                    break;
                }
            case "01":
                {
                    dt.locations.Add(Parse01(lines[i]));
                    break;
                }
            case "00":
                {
                    dt.reservations.Add(Parse00(lines[i]));
                    break;
                }
        }
    }
    return dt;
}

public static startup Parse11(string line)
{
    var ts = new startup();
    ts.code = line.Substring(2, 5);
    ts.invoice = line.Substring(7, 7);
    ts.amount = Decimal.Parse(line.Substring(14, 13));
    ts.model = line.Substring(63, 4);
    ts.brutto = Decimal.Parse(line.Substring(95, 13));

    return ts;
}

And I get

System.NullReferenceException: Object reference not set to an instance of an object.

at the line dt.tranches.Add(Parse11(lines[i])); Where my problem is and how can I fix it?

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
AlIon
  • 347
  • 5
  • 25
  • 1
    Looks like `dt.tranches` is not set. Apparently you expect the constructor `TranchesDt` to set it, but there is no explicit constructor that does, so you need to add it there, or just set the property yourself after creating the TranchesDt instance. – GolezTrol Sep 08 '17 at 09:57
  • The lists in the TranchesDt aren't initialized. In the constructor of the class you can do something this.tranches = new list() – Luc Sep 08 '17 at 09:58

1 Answers1

2

You never initialize List instances, thus dt.tranches is null. (as the other two list isntances)

Add this lines of code after

TranchesDt dt = new TranchesDt();

dt.tranches  = new List<startup>();
dt.reservations = new List<reservation>();
dt.locations = new List<location>();

Look out for syntax errors.

Dimitri
  • 2,798
  • 7
  • 39
  • 59