I was too excited when object initializer appeared in C#.
MyClass a = new MyClass();
a.Field1 = Value1;
a.Field2 = Value2;
can be rewritten shorter:
MyClass a = new MyClass { Field1 = Value1, Field2 = Value2 }
Object initializer code is more obvious but when properties number come to dozen and some of the assignment deals with nullable values it's hard to debug where the "null reference error" is. Studio shows the whole object initializer as error point.
Nowadays I use object initializer for straightforward assignment only for error-free properties.
How do you use object initializer for complex assignment or it's a bad practice to use dozen of assigments at all?
Thank you in advance!
Well, my main beef with object initializers is that they require a mutable type to start with: where possible, I prefer to use immutable types. Having said that, when an object initializer will work (e.g. for UI controls) I tend to use them.
I would possibly think twice if the values for the assignments were particularly complicated to compute - in particular, you have to be able to get the value in a single expression, and that may end up being less readable than computing it over several statements... but that's relatively rare in situations where this is feasible to start with.
I can't say I've had any problems with exceptions during property assignments with object initializers - it's just not something that comes up for me. If it did, I'd probably try to write a failing unit test anyway, at which point code usually becomes easy to fix without the debugger anyway.
Obviously moderation is always a good thing - I'm not suggesting taking this to extremes... but if you're setting a dozen properties, using an object initializer wouldn't be as much of a concern to me as having a dozen properties to set to start with. Are any of these dozen properties related? Should those be encapsulated together somehow? (In some cases that is fine - again, particularly with UI controls - but often it's not.)
If you're debugging your application then you should in most cases still be able to use VS' debugging tools to determine which assignment is causing the null reference.
However, if you split the assignment across multiple lines, I think VS will point to the right line when an exception is thrown:
MyClass a = new MyClass {
Field1 = Value1,
Field2 = Value2 };
Note: I don't do this myself, so be gentle about my (possibly) horrid line-breaking style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With