I have some custom classes defined that include lists of other classes like so:
public class Unit
{
public string Name { get; set; }
public List Contains { get; set; }
}
public class Group
{
public string Name { get; set; }
public Type Type { get; set; }
public int Number { get; set; }
}
public static Type basic_1 = new Type() { Name = "basic_1", Number = 1, Cost = 13 };
The basic idea is that you have a unit which contains a list of groups, each with a different type. The type contains specific properties while the classes that contain them are organizational in nature.
I then try to start building out these classes like so:
Unit unit1 = new Unit() { Name = "Unit 1" };
Group group1 = new Group() { Name = "Group 1", Number = 10, Type = basic_1 };
unit1.Contains.Add(group1);
But here I receive the error (on the Add
method) "Object reference not set to an instance of an object." Looking at the locals in the debugger I can see that the Unit
, Group
and Type
were all created successfully and the group1
contains all the Type
values it's supposed to, but unit1.Contains
is null.
What am I doing wrong? FYI I've never done something like this before so I don't even know if it's possible, but it seems to work fine up until this point.
Answer
Your List
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 Contains { get; set; }
public Unit()
{
Contains = new List();
}
}
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 Groups { get; set; }
public Unit()
{
Groups = new List();
}
}
No comments:
Post a Comment