Sunday, 6 November 2016

c# - Add element to null (empty) List Property





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 AllAntsAtMap { get; set; }


[...]




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

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

foreach (Ant ant in ants)
{
AddAntToMap(ant);
}
}


[...]


Answer



Initialize the list in the constructor:




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

...
}



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...