Reputation: 72
I'm new to programming and this may be a simple issue but I can't seem to figure it out. I have the following 2 classes in my program:
public class TrackingObject
{
public int OrderId { get; set; }
public int ProjectCount { get; set; }
public IList<ProjectInfo> Projects { get; set; }
}
public class ProjectInfo
{
public int ProjectId { get; set; }
public string ProjectType { get; set; }
public int ImageCount { get; set; }
}
For testing I created a console application and used the following code:
static void Main(string[] args)
{
TrackingObject oTracking = new TrackingObject();
ProjectInfo pInfo = new ProjectInfo();
oTracking.OrderId = 1;
oTracking.ProjectCount = 1;
pInfo.ProjectId = 1;
pInfo.ProjectType = "CANVAS";
pInfo.ImageCount = 1;
oTracking.Projects.Add(pInfo);
Console.WriteLine(oTracking.Projects.Count);
Console.ReadLine();
}
When I run the application it throws a NullReferenceException was unhandled on the following line:
oTracking.Projects.Add(pInfo);
I understand enough to know that the exception is because oTracking.Projects is NULL. What is the correct way to accomplish what I am attempting? Any guidance will be most appreciated.
Upvotes: 0
Views: 125
Reputation: 949
Combination of I4V's answer and first comment on that answer:
public class TrackingObject
{
public int OrderId { get; set; }
public int ProjectCount { get; set; }
public IList<ProjectInfo> Projects { get; set; }
public TrackingObject() {
this.Projects = new List<ProjectInfo>();
}
//This constructor optional, but since you're using an IList, may as well
//let the user pass in an IList of a different type if they chose
public TrackingObject(IList<ProjectInfo> defaultList) {
this.Projects = defaultList;
}
}
Upvotes: 2
Reputation: 4124
static void Main(string[] args)
{
TrackingObject oTracking = new TrackingObject();
ProjectInfo pInfo = new ProjectInfo();
oTracking.OrderId = 1;
oTracking.ProjectCount = 1;
pInfo.ProjectId = 1;
pInfo.ProjectType = "CANVAS";
pInfo.ImageCount = 1;
oTracking.Projects = new List<ProjectInfo>();
oTracking.Projects.Add(pInfo);
Console.WriteLine(oTracking.Projects.Count);
Console.ReadLine();
}
Upvotes: 0
Reputation: 70728
Check if the object if null
, if it is assign a new instance:
if (oTracking.Projects == null) {
oTracking.Projects = new List<ProjectInfo>();
}
Upvotes: 1
Reputation: 20764
Projects
needs to be initialized:
oTracking.Projects = new List<ProjectInfo>();
Upvotes: 0
Reputation: 35353
Add oTracking.Projects = new List<ProjectInfo>()
before adding items to it.
Upvotes: 5