Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read required attribute in C# 11 by reflection

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.

like image 373
Sayed Javad Sayedi Avatar asked Dec 14 '25 06:12

Sayed Javad Sayedi


1 Answers

Required members are decorated with RequiredMemberAttribute.

bool isRequired = typeof(C1).GetProperty("P1").GetCustomAttribute<RequiredMemberAttribute>() != null;

This was easy to discover using SharpLab.

like image 163
canton7 Avatar answered Dec 16 '25 22:12

canton7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!