8

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);
        }
    }

[...]

Sinmson
  • 159
  • 1
  • 3
  • 12
  • 1
    Any reason why the property is virtual and then overridden in a derived class? You really only need to declare it once. Overriding adds no benefit here. – siride Sep 10 '15 at 14:39

5 Answers5

17

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.)

Heinzi
  • 151,145
  • 51
  • 326
  • 481
12

It is much simpler in C# 6:

protected List<Ant> AllAntsAtMap { get; set; } = new List<Ant>();
Kędrzu
  • 2,265
  • 11
  • 21
2

You should initialize AllAntsAtMap before usage. You can use the constructor for that:

public Quadrangle()
{
    AllAntsAtMap = new List<Ant>();
}
John C
  • 2,732
  • 2
  • 31
  • 46
burning_LEGION
  • 12,532
  • 8
  • 36
  • 48
1

You need to instantiate the list before adding:

this.AllAntsAtMap = new List<AllAntsAtMap>();
David
  • 181
  • 3
  • 15
1

Initialise the list in the constructor.

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

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

}

You don't need to override the list property in Quadrangle unless you specifically need a separate list from the base class. If you do have a separate list in the child class then you need to initialise that list in the child class constructor.

If the base class shouldn't have an implementation of the list property, then you should make it abstract instead of virtual, and initialise it in the child class where the property is implemented.

Guffa
  • 640,220
  • 96
  • 678
  • 956