technomalogical
technomalogical

Reputation: 3002

Debugging a C# Object Initializer

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?

Upvotes: 11

Views: 2229

Answers (3)

JMarsch
JMarsch

Reputation: 21751

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.

Upvotes: 4

David Yancey
David Yancey

Reputation: 2030

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

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564741

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.

Upvotes: 14

Related Questions