0

I have a 2 classes Record and Pos. The class Record has a List.

public class Record
{
    public string RecordNr { get; set; }
    public List<Pos> Positions { get; set; }
    public bool barred { get; set; }

    public Vorgang()
    {
        RecordNr = "";
        Positions = null;
        barred = false;
    }
}

public class Pos
{
    public string PosNr { get; set; }
    public string ArtNr { get; set; }

    public Pos()
    {
        PosNr = "";
        ArtNr = "";
    }
}

How can I add a item to List in the Record class.

Pos cPos = new Pos 
{
   ArtNr = "35454",
   PosNr = "1",
};

Record cRec = new Record ();
cRec.Positions.Add(cPos);

Why I get a System.NullReferenceException?

pekabo
  • 1
  • 1
  • Because the List is null. You need to initialize it: `Positions = new List();` Also: `public Vorgang() { }` is not valid syntax. That's supposed to be `public Record() { }`. – Dennis_E Sep 02 '16 at 13:17
  • "Positions = null;" "cRec.Positions.Add(cPos);" Positions is null. –  Sep 02 '16 at 13:17
  • A more specific duplicate is [this](http://stackoverflow.com/q/39016363/6400526) - Exactly same case – Gilad Green Sep 02 '16 at 13:17
  • Thanks Dennis_E: System.NullReferenceException is gone by Positions = new List() instead of Positions = null; – pekabo Sep 02 '16 at 13:31

0 Answers0