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

Get attribute from record

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.

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

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:).

>Solution :

You’re looking in the wrong place: when using the "braceless" record syntax in C#, attributes placed on members are actually parameter attributes.

You can get the DisplayAttribute from [Display] String FirstName like so:

ParameterInfo[] ctorParams = typeof(TestRecord)
    .GetConstructors()
    .Single()
    .GetParameters();
        
DisplayAttribute firstNameDisplayAttrib = ctorParams
    .Single( p => p.Name == "FirstName" )
    .GetCustomAttributes()
    .OfType<DisplayAttribute>()
    .Single();
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