1

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

4
  • @Dai Why are you editing perfectly valid and compiling C# code? See learn.microsoft.com/en-us/dotnet/core/tutorials/… Commented Mar 23, 2022 at 8:25
  • Because your record type 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. Commented Mar 23, 2022 at 8:27
  • 1
    Here I have replaced your DisplayAttribute to NotNullAttribute (since DataAnnotations can'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. Commented Mar 23, 2022 at 8:38
  • 2
    If you want to place the attribute on the generated property, use [property: Display] string FirstName Commented Mar 23, 2022 at 8:48

1 Answer 1

7

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.