I was wondering, what is the preferred way to construct a new object in C#?
Take a Person class:
public class Person
{
private string name;
I tend to prefer a very simple constructor with property intializers. I find it leads to more explicit code. The only data I would pass to the constructor is information that I do not want the user of my class to alter once the class is created.
For settings the properties manually, they would have to be declared public, and you may want the class members to be private. In which case the constructor is the way to go, or write methods to get/set them or use an accessor.
The second way is just syntactic sugar for setting the properties manually:
Person p = new Person();
p.Name = "name";
p.Age = 24;
You're also not depending on the constructor which may not initalize all the properties you want to set.
If your class has a constructor which requires these two parameters, you don't get around to explicitly call that constructor.
Setting the values in the constructor, makes those properties mandatory, so this means you cannot create a new instance, without settings those properties. In some situations this is preferable, in other situations this is not prefferable.
A few thoughts:
You need public properties to use Object Initializers. So if there's something you don't want to expose, you have to initialize them by constructor parameter.
If you check IL, you will find Object Initializer is not "atomic". If you write code like this (not that I recommend, just an example):
using (p = New Person() {Name = GetName(), Age = GetAge()})
{
//blah, blah
}
If there's an exception in GetAge()
, you will create a instance of Person
in a corrupted state. Worse, you can never enter the using scope and that instance will not be disposed as you would imagine.