Skip to content

Treat .NET 7 required properties as actually required by default #862

Open

Description

@DoctorKrolic

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

Activity

  1. Orace commented on Dec 12, 2022

    @Orace

    Using sharplab.io, it appears that a RequiredMemberAttribute is added to the required properties.

    Search for this attribute is a trivia.

  2. Orace commented on Dec 13, 2022

    @Orace

    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.

    1. We can make Required = true mandatory on required properties, which is redundant and against the purpose of this issue (Treat .NET 7 required properties as actually required by default).

    2. We can change the type of the Required attribute property to a try-state (unset, true, false) with an unset default value, which will be treated:

      • as true in the case of a required property
      • as false in other cases
    3. We can stay silent and ignore Required = false on required properties.

    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?

  3. DoctorKrolic commented on Dec 13, 2022

    @DoctorKrolic
    Author

    Required = false is 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...

  4. Orace commented on Dec 13, 2022

    @Orace

    A quick look to the IL shows it unfortunately is 😒

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions