Home > other >  C# Identify Which Property Caused a Null Reference Exceptions in Object Initialization in Visual Stu
C# Identify Which Property Caused a Null Reference Exceptions in Object Initialization in Visual Stu

Time:11-24

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?

CodePudding user response:

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.

CodePudding user response:

Consider inspecting your browser and take note of which property is empty. My advise

  • Related