user33276346
user33276346

Reputation: 1759

C# null reference exception, how to spot the culprit in the specified line

We are all tired of this kind of exceptions, but is there a way to quickly find the offending thing? Usually this kind of exception is thrown in a line like this:

var myVar = somethingUninitallized.property;

And it's easy to see that the right hand side of the assignment is the cause. However there are times when the lines are long like this:

var myVar = x.DoSomething(y.FirstDoThis(isThisInitiallized).aProperty, z.ThenDoThis(whatAboutThis).anotherProperty).ComplicatingThings().thisHappensSometimes;

And we get the exception on that line. Yes we could have written the code differently, but could be the case that we might be debugging other people's code and modifying it would require to recompile for 15 minutes, require authorization, or any other impediment. This is a trivial example, and I can think on linq too, but surely there are other even more complicated scenarios. I usually inspect each thing one by one still in the year 2020.

Is it impossible to have from the debugger tools or somehow, which is the thing with a null reference?

Upvotes: 1

Views: 1949

Answers (1)

Rufus L
Rufus L

Reputation: 37070

Here's an answer copied from Debugging System.NullReferenceException, writen by Thomas Ardel:


Using Null Reference Analysis in Visual Studio

If you are on Visual Studio 2017 or newer, you will have the Null Reference Analysis feature available. With this in place, Visual Studio can show you exactly what is null. Let's use this example of method-chaining:

var street = service.GetUser().Address.Street;

To enable the analysis go to Debug | Windows | Exception Settings. Check Common Language Runtime Exceptions (if not already checked) or extend the node and check the exceptions you are interested in.

In this case, you can check System.NullReferenceException. When running the code, the debugger breaks on the NullReferenceException and you now see the Exception Thrown window:

enter image description here

Voila! The window says "ConsoleApp18.User.Address.get returned null". Exactly what we wanted to see.

Upvotes: 5

Related Questions