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; private int age; //Omitted.. }
Should I create it to use:
New Person("name", 24);
or
New Person() { Name = "name", Age = 24 };
Is it just a matter of taste or is there a good reason to use one over the other?
I can imagine that one should only use the required fields in the constructor and optional fields not as constructor parameters but by using properties.
Am I right in that?
In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
The preferred way depends on your design.
Constructor properties are for items that your object requires in order to be correctly constructed. That is to say, any properties the object should have in order to be initialized need to be in the constructor (you don't usually want a partially intialized object after the constructor is called unless you're creating a factory or builder pattern and the constructor is hidden from all but the factory/builder).
Property intializers are best for additional configuration after a constructor that is required by your particular use case but is not required for the object to be considered initialised.
For example, you could have an object that represents a person. A person needs a name and an age to be initialised, but the address they live at is an optional configuration. So, the name and age are constructor parameters, and the address is a read/write property.
Person johnDoe = new Person("John Doe", 24) { Address = "42 Adams Street" };
It really depends on the scenario. The property approach has a lot of convenience, in that you don't have to duplicate the assignments in the constructor. Furthermore, most data-binding scenarios like to be able to create new objects, for which they usually use the parameterless constructor, so that is a big advantage.
However, for immutable types, the constructor approach is the only sensible option. Interestingly (perhaps) the named/optional parameters in C# 4.0 allow something similar to object initalizers for immutable types - see here.
The constructor approach is also very popular for Inversion of Control frameworks, as it clearly advertises what that class needs in order to function.
You may need to mix and match, but usually more property-style than constructor-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