Home > Back-end >  Get attribute from record
Get attribute from record

Time:03-23

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

CodePudding user response:

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();
  • Related