Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Identify Which Property Caused a Null Reference Exceptions in Object Initialization in Visual Studio

Let's say I am a initializing a new object at once that has many properties. One of them causes a null reference exception, but when you use the debugger it passes through the entire code initialization block at once. Is there any easy way to find which property caused the error. Note that the object properties maybe many types so some of the types are allowed to be null.

ex object initalization

var obj = new Obj{
prop1 = x,
prop2 = y,
prop3 = f,
prop4 = r,
prop5 = h,
prop6 = k,
prop7 = w,
prop8 = l,
prop8 = m,
prop9 = e,
prop10 = a 
};

One of these properties caused the null reference exception but you don't know which and the debugger passed through the entire block at once. Is there a method to identify this with visual studio?

like image 981
nightwolf555 Avatar asked Oct 23 '25 03:10

nightwolf555


1 Answers

Set a breakpoint on the assignment to obj and open the Locals window. Observe the values of the variables that you are assigning to the properties of obj. Aside from that, Visual Studio itself doesn't have much built-in to help you in this regard (that I'm aware of or can recall at the moment) aside from tooltips.

This is the biggest drawback of object and list initializers. If you're assigning to lots of properties, the exception is thrown on the first line of the initialization block, as you've observed. It's incredibly annoying, and can make things difficult to track down.

If you're fortunate enough to be using a fairly advanced refactoring addon (like Resharper or CodeRush), there should be a refactoring to convert an object initializer into direct property assignments and back again. This would allow you to convert the object initializer into property assignments, debug the code so you can isolate the problem statement quickly, resolve it, and then convert the code back into an object initializer.

like image 159
Mike Hofer Avatar answered Oct 25 '25 18:10

Mike Hofer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!