Your List<Group> Contains
never gets initialized, so when you try to access it, you get a null reference exception. Essentially all null reference exceptions are the same, you're trying to use an object that's null.
In this case, let's just add a default constructor to initialize the list for us.
public class Unit
{
public string Name { get; set; }
public List<Group> Contains { get; set; }
public Unit()
{
Contains = new List<Group>();
}
}
By the way, Contains
is a terrible name for a list. Contains
is usually a function call, as it's a verb. Usually better to use a noun for a collection, such as Groups
.
public class Unit
{
public string Name { get; set; }
public List<Group> Groups { get; set; }
public Unit()
{
Groups = new List<Group>();
}
}