Home > Blockchain >  C# 11 - detect required property by reflection
C# 11 - detect required property by reflection

Time:11-09

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? I can't find any obvious method or property in PropertyInfo. There is GetRequiredCustomModifiers but that seems to have a different function.

PropertyInfo prop = typeof(Example).GetProperty("Value");
//bool isRequired = prop ...?

CodePudding user response:

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.

  • Related