views:

412

answers:

3

Does anyone have any tips for debugging exceptions in a C# object initializer block? The object initializer syntax is basically all or nothing, which can make it especially difficult to troubleshoot inside of a LINQ query. Short of breaking the object creation out to a separate method, is there anything I can do to see which property setter is throwing an exception?

+6  A: 

Disabling the option to step over property setters [Step over properties and operators (Managed Only)] can allow you to step into the property setters.

Otherwise, the best option is often to just break it out and debug it outside of the LINQ statement. You can wrap your initialization parameters into an anonymous type in linq, and construct your object(s) outside of your linq statement for debugging purposes.

Reed Copsey
Could you explain what you mean by "wrap your initialization parameters into an anonymous type"? Would I pass the anonymous type to the constructor somehow, or just create a utility factory method that would assign the properties?
technomalogical
Right now, from the sounds of it, you're using your query results to construct your objects, and you believe that's causing an error (on the object construction). Instead, just return the query results, then build your objects in a separate step afterwards (using the results), so you can avoid the object initializer blocks.
Reed Copsey
But is it possible to somehow pass an anonymous type to a constructor?
wcm
No. You'd need to pass each of the members from teh anonymous type to the constructor, ie: MyObj obj = new MyObj(anonInst.Param1); anonInst.Prop1 = anonInst.SomeProperty; ... etc.
Reed Copsey
I think what @wcm and I were getting hung up on was passing the IEnumerable of anonymous type to another method to assemble. It just dawned on me that what you're suggesting is just holding the IEnumerable in a seperate var and doing a foreach over it. I've marked this as the best answer.
technomalogical
@technomalogical: Yes, that was exactly what I was suggesting. I'm sorry if it wasn't clear.
Reed Copsey
+1  A: 

Break it out of the object initializer block where your setting each property individually. That way you can actually step into the code.

David Yancey
+2  A: 

Have you set up VS to break when an exception is thrown? (the default is to break only on unhandled exceptions). Debug | Exceptions, and check "thrown".

That alone is probably not an answer to your question, but it might help with the debugging.

Beyond that, you could temporarily break your code out of the initializer block (just for debugging), and then if you want, you can reinstate the initializer block once you have the code working.

JMarsch