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);
}
}
[...]
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With