4

C# 11 added support for required properties.

public class Example
{
    public required string Value { get; set; }
}

How do I detect that the property is declared as required by reflection?

Please note this is a different question from Return a list of all required properties in a class because that question is from 2017 about a custom attribute, this is about required property keyword which is new in C# 11 (2022).

PropertyInfo prop = typeof(Example).GetProperty("Value");
//bool isRequired = prop ...?
Mirek
  • 4,013
  • 2
  • 32
  • 47

1 Answers1

8

If we run your code through sharplab, we see that your code becomes:

[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
[RequiredMember]
public class Example
{
    [CompilerGenerated]
    private string <Value>k__BackingField;

    [RequiredMember]
    public string Value
    {
        [CompilerGenerated]
        get
        {
            return <Value>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <Value>k__BackingField = value;
        }
    }

    [Obsolete("Constructors of types with required members are not supported in this version of your compiler.", true)]
    [CompilerFeatureRequired("RequiredMembers")]
    public Example()
    {
    }
}

So... just test for the existence of the RequiredMemberAttribute on the property via Attribute.IsDefined(propertyInfo, typeof(RequiredMemberAttribute)). I guess you should also test for RequiredMemberAttribute on the type too.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900