c# object initializer complexity. best practice

Posted by Andrew Florko on Stack Overflow See other posts from Stack Overflow or by Andrew Florko
Published on 2010-06-18T07:43:49Z Indexed on 2010/06/18 7:53 UTC
Read the original article Hit count: 247

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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about best-practices