I am pretty happy with the new feature that provides an opportunity to use required
keyword instead of constructors.
Still, I wonder are there any downsides? What are the cases where constructors are preferable to required
keyword?
While in most cases, constructors can be replaced by required
, I can think of some obvious, albeit relatively uncommon, cases where you would still need to use constructors.
This is disallowed by design. The override of a required property must also be required, whereas derived class constructors can easily "remove" a parameter from a base class constructor, like:
public BaseClass(string p) { }
public DerivedClass(): base("some default value") { }
If you want to do something like that with required
, you cannot :(
Required properties can only be at least as visible as their enclosing type. This means if your class is public, no internal, protected or private required properties for you!
On the other hand, constructors can initialise properties of all access levels.
If you have a situation where the initialisation of the properties depends on multiple different parameters, like
public MyClass(string p1, string p2, string p3) {
this.Property1 = MakeSomethingFrom(p1, p2);
this.Property2 = MakeSomethingElseFrom(p2, p3);
}
then I don't think it is possible (or at least it is very hard) to rewrite it with required
. I cannot think of how one can do it.
Another way of explaining this case is when you don't want to store an initialisation parameter in a field/property - you just want to do something with it, and discard it. That is when constructors are more suitable, since required
can only be applied to fields and properties.