How can this code throw a NullReferenceException?
Posted
by Davy8
on Stack Overflow
See other posts from Stack Overflow
or by Davy8
Published on 2009-05-08T01:26:17Z
Indexed on
2010/05/31
4:52 UTC
Read the original article
Hit count: 284
I must be going out of my mind, because my unit tests are failing because the following code is throwing a null ref exception:
int pid = 0;
if (parentCategory != null)
{
Console.WriteLine(parentCategory.Id);
pid = parentCategory.Id;
}
The line that's throwing it is:
pid = parentCategory.Id;
The console.writeline is just to debug in the NUnit GUI, but that outputs a valid int.
Edit: It's single-threaded so it can't be assigned to null from some other thread, and the fact the the Console.WriteLine successfully prints out the value shows that it shouldn't throw.
Edit: Relevant snippets of the Category class:
public class Category
{
private readonly int id;
public Category(Category parent, int id)
{
Parent = parent;
parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this));
Name = string.Empty;
this.id = id;
}
public int Id
{
get { return id; }
}
}
Well if anyone wants to look at the full code, it's on Google Code at http://code.google.com/p/chefbook/source/checkout
I think I'm going to try rebooting the computer... I've seen pretty weird things fixed by a reboot. Will update after reboot.
Update: Mystery solved. Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.
© Stack Overflow or respective owner