views:

96

answers:

3

When debugging C# with Visual Studio, is it possible to see WHICH object reference on a given line of code caused a NullReferenceException?

I have what seems like an odd situation where, occassionally, when running a debug build of an application from Visual Studio, I will get a NullReferenceException at a certain line.

Visual Studio will pop up the exception assistant box pointing at the line, but none of the 3 object references used on that line are null at that point.


The line is:

myClassInstance.myMethod(myOtherClassInstance.IPAddressInstance.ToString());

Both of my class instances are non-null, as is the IPAddress instance (which has its intended value).

+1  A: 

If you're calling code marked with the [DebuggerNonUserCode] attribute, the problem might be in framework code, not on that line.

In any case, do you have a specific example that you could post?

Lasse V. Karlsen
Updated the question with the line.
frou
+2  A: 

Be careful of functions that return null objects. This got me once and isn't very clear within the debugger. Check this out:

public class FooBar
{
    public int ReturnInt() { return 0; }
}

public FooBar ReturnNullObject()
{
    return null;
}

// Execution code:
int exceptionalInt = ReturnNullObject().ReturnInt();

Edit: according to your edit, make sure IPAddressInstance isn't returning null.

Edit: you might want to break the single line into a couple of lines. This should help.

var ip = myOtherClassInstance.IPAddressInstance;
var ipString = ip.ToString();
myClassInstance.myMethod(ipString);
xanadont
A: 

Set a breakpoint at that line at do "step-into" till you get NRE.

No magic, right? Some code try to dereference null.

Even if you do smth like A.Property.Property2.ToString() as Visual Studio says none of them are null, the problem is then in ToString() method, which lies in an assembly, that Visual Studio do not enter in Debug.

modosansreves