Should I use an object initializer or a constructor?
c#, constructor, object-initializer
Solution
I currently see the following problems with using them:
- The properties that are assigned have to be changeable. This seems undesirable because if the data is passed to a constructor I can check it there and make object creation fail if the data provided is insufficient or wrong. If data can be assigned with a property I suddenly have to figure out what the state of my object is, whether everything is properly created yet or which other state I might be in.
- The properties that are assigned have to be public. This means that access to things that might otherwise be private will have to be exposed and then later restricted by using an interface or something like that.
So my working theory is: Don't use object initializers they encourage stupid things.
Problem
I have just learned about object initializers and was wondering what the best practices for when to use them are. This is what I read about them: http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx It makes it clear that they are necessary for creating anonymous types but I would like to know if I should try to prefer them to normal constructors in all the other cases.