0

I got a class who looks like this.

public class PostUndKey
{
    public string Key { get; set; }
    public List<int> Id { get; set; }
    public List<string> von_datum { get; set; }
    public List<string> bis_datum { get; set; }
}

In my Code i use something like this.

PostUndKey x = new PostUndKey();
var z = 42;
x.Id.Add(z);

And i always get the Null Reference Exception. Can someone explain this to me pls i dont get it.

Thanks

1 Answers1

2

You need to create an instance of List<int> and assign it to Id property. List<T> is a reference type and default value for reference type is null. For example:

PostUndKey x = new PostUndKey();
x.Id = new List<int>();
var z = 42;
x.Id.Add(z);

Or initialize Id for PostUndKey instance creation:

public class PostUndKey
{
    public string Key { get; set; }
    public List<int> Id { get; set; } = new List<int>();
    public List<string> von_datum { get; set; }
    public List<string> bis_datum { get; set; }
}

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132