Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to null (empty) List<T> Property [duplicate]

I got a problem.

The problem is that I try to ad an object to a list of this objects. This list is a property, no error, but when I run it fails at this point, becouse: "NullReferenceException". Sounds logical, becouse the Property of the list is "null", but I cant declare a property, can I?

Her is some Code snipped:

class Maps
{
    protected virtual List<Ant> AllAntsAtMap { get; set; }

[...]

class Quadrangle : Maps
{
    protected override List<Ant> AllAntsAtMap { get; set; }

    public override void AddAntToMap(Ant ant)
    {
        AllAntsAtMap.Add(ant);  //Error here
    }
    public override void AddAntsToMap(List<Ant> ants)
    {
        foreach (Ant ant in ants)
        {
            AddAntToMap(ant);
        }
    }

[...]

like image 253
Sinmson Avatar asked Sep 10 '15 14:09

Sinmson


2 Answers

Add element to null (empty) List Property

null and an empty list are two different things: Adding an element to an empty list works fine, but if your property is null (as all reference-type properties are initially null), you need to initialize it with an empty list first.

You could use an auto-property initializer for that (see Kędrzu's answer), or you could manually initialize the list in the constructor:

class Maps
{
    public Maps()
    {
        AllAntsAtMap = new List<Ant>();
    }

    ...
}

(Since the property is declared in the superclass Maps, I'd do the initialization there rather than in the subclass Quadrangle.)

like image 165
Heinzi Avatar answered Sep 25 '22 08:09

Heinzi


It is much simpler in C# 6:

protected List<Ant> AllAntsAtMap { get; set; } = new List<Ant>();
like image 33
Kędrzu Avatar answered Sep 24 '22 08:09

Kędrzu