Thoughts on Object Initializer Syntax?

When writing the following code

var obj = new SomeClass(); obj.Property1 = 1; obj.Property2= someNullReference.someInvalidProperty; 

Visual Studio (or Resharper perhaps), suggests converting it into the following:

var obj = new SomeClass(){ Property1 = 1, Property2 = someNullReference.someInvalidProperty }; 

I don’t see any advantages with Object Initializer Syntax. Infact, it makes debugging a nightmare if you have a large number of properties since an exception thrown anywhere in the Object Initializer Syntax will only show as the first line in a stack trace. It’s impossible to trace which line exactly the exception was thrown on. In the above example, an exception would be thrown while trying to evaluate Property2 = someNullReference.someInvalidProperty, but the stack trace will show the problem happened on line 1.

What is the advantage of Object Initializer Syntax? The readability of the code is almost exactly the same, and you lose valuable debugging information. Am I missing the point of this syntax?

submitted by /u/ohThisUsername
[link] [comments]

Leave a Reply