In C# 11 Microsoft introduced required attribute for field and properties as member of class. I need to read this attribute in reflection. How can I do it? For example in class C1 and property P1 we need to read required attribute.
class C1
{
public int required P1 { get; set; }
}
.
..
Type targetType = typeof(C1);
PropertyInfo propertyInfo = targetType.GetProperty("P1");
propertyInfo.?????
propertyInfo.Attributes and enum System.Reflection.TypeAttributes does not have required item.
Required members are decorated with RequiredMemberAttribute.
bool isRequired = typeof(C1).GetProperty("P1").GetCustomAttribute<RequiredMemberAttribute>() != null;
This was easy to discover using SharpLab.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With