简体   繁体   中英

C# 11.0 required feature

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.

Specialising a required property in a derived class so that it is not required

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:(

Where the properties are less visible than the enclosing type

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.

Where the initialisation isn't one-to-one

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM