I'm looking for a way to get the attribute defined on a record constructor "field".
// See https://aka.ms/new-console-template for more information using System.ComponentModel.DataAnnotations; var property = typeof(TestRecord) .GetProperties() .First( x => x.Name == nameof(TestRecord.FirstName) ); var attr0 = property.Attributes; // NONE var attr1 = property.GetCustomAttributes( typeof(DisplayAttribute), true ); // empty var property1 = typeof(TestRecord) .GetProperties() .First( x => x.Name == nameof(TestRecord.LastName) ); var attr2 = property1.Attributes; // NONE var attr3 = property1.GetCustomAttributes( typeof(DisplayAttribute), true ); // Works public sealed record TestRecord( [Display] String FirstName, [property: Display] String LastName ); I'm able to get the attribute on LastName targeting the property (using property:).
But I'm not able to find a way to retrieve the attribute on FirstName.
I'm sure there is a way to read the attribute data... at least ASP.NET is able to read validation and display attributes specified without targeting the property (property:).
recordtype was buried below the fold in StackOverflow's scrolling code area, I couldn't see it at all at first, and you had inconsistent indenyation and didn't have the correct code-language hints in your post. Also, not everyone is using VS2022.DisplayAttributetoNotNullAttribute(sinceDataAnnotationscan't be used easily in sharplab). If you look at the decompiled code then you can see that this attribute is used only inside constructor but not at the property itself.[property: Display] string FirstName