Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can this code throw a NullReferenceException?

Tags:

c#

nunit

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.

like image 740
Davy8 Avatar asked Dec 06 '22 06:12

Davy8


1 Answers

Based on all the info so far, I think either "the line that's throwing is" is wrong (what makes you think that), or possibly your 'sources' are out of sync with your built assemblies.

This looks impossible, so some 'taken for granted assumption' is wrong, and it's probably the assumption that "the source code you're looking at matches the process you're debugging".

like image 89
Brian Avatar answered Dec 09 '22 14:12

Brian