Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# 11 – detect required property by reflection

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 ...?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading