Add element to null (empty) List<T> Property
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.)
It is much simpler in C# 6:
protected List<Ant> AllAntsAtMap { get; set; } = new List<Ant>();
You should initialize AllAntsAtMap
before usage. You can use the constructor for that:
public Quadrangle()
{
AllAntsAtMap = new List<Ant>();
}