c# object initializer complexity. best practice
- by Andrew Florko
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!