Skip to content

[API Proposal]: Allow DisplayAttribute on structs and enums #117040

Open
@Pankraty

Description

@Pankraty

Background and motivation

Back in 2016 [DisplayAttribute] was made applicable for class declarations (#17139). Possible use cases were listed as

  • Auto-generate form captions
  • Auto-generate report captions
  • Use this information to extend nested property captions (like Person.Details.Address could get a label as Personal info / Address)
  • Auto-generate documentation (consuming Description and Order for example)
  • etc.

Those are all valid use cases, but they also apply to enums and structs where this attribute is not allowed.

In my use case I wanted to generate API method description based on enum's display name.

API Proposal

[AttributeUsage(
    AttributeTargets.Property |
    AttributeTargets.Field |
    AttributeTargets.Parameter |
    AttributeTargets.Method |
+   AttributeTargets.Enum |
+   AttributeTargets.Struct |
    AttributeTargets.Class,
    AllowMultiple = false)]
public sealed class DisplayAttribute : Attribute

API Usage

using System.ComponentModel.DataAnnotations;

[Display(Name = "This works well")]
public class SampleClass;

[Display(Name = "This works well")]
public record SampleRecord;

[Display(Name = "This does not compile")]
public struct SampleStruct;

[Display(Name = "This does not compile")]
public enum SampleEnum
{
    [Display(Name = "This works well")]
    EnumMember
}

[Display(Name = "This does not compile")]
public record struct SampleRecordStruct;

The proposal is to make all these samples working the same way, because there is no practical sense why structs and enums may not have Display attribute specified while classes may.

All the code needed for getting attributes from enum or struct definition exists, it's just a matter of making the attibute possible to assign to them.

        typeof(SampleStruct).GetCustomAttributes(typeof(DisplayAttribute), inherit: false);
        typeof(SampleRecordStruct).GetCustomAttributes(typeof(DisplayAttribute), inherit: false);
        typeof(SampleEnum).GetCustomAttributes(typeof(DisplayAttribute), inherit: false);

Alternative Designs

No response

Risks

I cannot see that this proposal can break any existing code: since DisplayAttribute is not assignable to enums and structs there should not be any logic relying on its existance on the type definition. This is just an enabler for applications using the attribute for documenting purposes or for showing human-readable descriptions on UI.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions