In C#, a default constructor (a constructor with no parameters) is silently added by the compiler when there is no explicit constructor available in a class. All the fields of the object will be set to their default values when a default constructor is invoked at runtime.
In the first example below, you can observe that when an object of the LawFirm
class is allowed to be created using a default constructor, the Name
field of type string on the object is set to null as an initial value, which is the default value for a reference type. This compels all consumers of the LawFirm
object to check for a null reference in the Name
field before accessing it because the object allowed itself to be created in an inconsistent state.
To avoid this, always ensure that the object is initialized in a consistent state through a parameterized constructor or a factory method. Design your classes in such a way that if an object of a class exists, it is in a consistent state. As shown in the second example below, an ArgumentNullException
is thrown if null is passed in the constructor, terminating the object creation.
Always design your classes with the aim of making life easier for the consumers. Think twice before you allow a default constructor to sneak in to your domain model.
public class LawFirm
{
public string Name { get; set; }
//Avoid this
public LawFirm()
{
}
}
public class LawFirm
{
public string Name { get; private set; }
//Ensure the object is created in a consistent state, always!
public LawFirm(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
}