Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Null object of a NullReferenceException

Tags:

c#

.net

I have a problem with a uge solution at work that gets a lot of "Object reference not set to an instance of an object" errors. What's the best way to determine the null object(s) causing the exception?

I can try catch all those exceptions in one place, but can't find a way to determine the member that is null so I can fix it properly.

try {
}
catch (Exception ex)
{
if (ex is ReferenceNullException)
ex.??
}
}

Since I can view the stacktrace it would be reasonable to think you could also get what caused the error.

like image 502
Bruno Silva Avatar asked Aug 27 '12 15:08

Bruno Silva


2 Answers

Think about it for a second. It's a NullReferenceException. That means you're trying to call a method or access a property on a NULL REFERENCE to an object. That means the object reference you're trying to access is EMPTY, null. It does not exist.

So what you're trying to find actually does not exist.

Normally to track down which object reference is null a debugger is used. Just set a breakpoint on the line causing the exception and inspect all variables to see which one is null.

Debugger is your greatest tool.

like image 107
Strelok Avatar answered Oct 18 '22 15:10

Strelok


If you are not able debug NullReferenceException with IDE in case that it only happens at customer side or it is difficult to reproduce, then NullReferenceException.StackTrace which has FUNCTION/FILE/LINE information will help you to locate the null object, NullReferenceException.ToString() also include StackTrace, For example:

System.NullReferenceException: Object reference not set to an instance of an object.

at WindowsFormsApplication3.Form1.button1_Click(Object sender, EventArgs e) in D:\vcs\WindowsFormsApplication3\WindowsFormsApplication3\Form1.cs:line 26

To enable line number for release build, pls check this post Display lines number in Stack Trace for .NET assembly in Release mode

like image 42
Joseph Ding Avatar answered Oct 18 '22 15:10

Joseph Ding