Dreampoet
Dreampoet

Reputation: 72

How can I correct a NullReferenceException in the following code?

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

Answers (5)

dwarduk
dwarduk

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

Kamran Shahid
Kamran Shahid

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

Darren
Darren

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

thumbmunkeys
thumbmunkeys

Reputation: 20764

Projects needs to be initialized:

 oTracking.Projects = new List<ProjectInfo>();

Upvotes: 0

I4V
I4V

Reputation: 35353

Add oTracking.Projects = new List<ProjectInfo>() before adding items to it.

Upvotes: 5

Related Questions