commandline
commandline copied to clipboard
Treat .NET 7 `required` properties as actually required by default
Code snippet:
public class Options
{
[Option]
public required int Port { get; init; }
[Option]
public required string Server { get; init; }
}
Expected behaviour: Both Port and Server are required and the parsing fails if at least on of them is not present.
Actual behaviour: They are not required, I still have to specify [Option(Required = true)] in order for it to work
Using sharplab.io, it appears that a RequiredMemberAttribute is added to the required properties.
Search for this attribute is a trivia.
Has mentioned by DoctorKrolic here
What if you have a required modifier and [Option(Required = false)]? I would say, it should throw because of conflicting settings. Please add test for such case
Required = false is the default case, hence, if we implement this, it will throw on default case.
-
We can make
Required = truemandatory onrequiredproperties, which is redundant and against the purpose of this issue (Treat .NET 7 required properties as actually required by default). -
We can change the type of the
Requiredattribute property to a try-state (unset,true,false) with anunsetdefault value, which will be treated:- as
truein the case of arequiredproperty - as
falsein other cases
- as
-
We can stay silent and ignore
Required = falseonrequiredproperties.
Option 2 looks pretty, but we must validate that it is not a breaking change (see this Jon Skeet post where he talk about the optional parameters). Does a bool? do the trick?
Required = falseis the default case, hence, if we implement this, it will throw on default case.
Uh, I see...
Does a bool? do the trick?
Having Required as a bool? can really be a win, so we infer null state to true if the property is required and false otherwise. I am afraid, this is a binary breaking change though...
A quick look to the IL shows it unfortunately is 😒