DisplayAttribute
When you apply [Display] to an enum member, Enum Utilities can generate methods that utilize each property of DisplayAttribute:
- Name
- ShortName
- Description
- ResourceType (optional, for resource-based localization)
Example
using System.ComponentModel.DataAnnotations;
[EnumGenerator]
public enum WeekDays
{
[Display(
Name = nameof(Strings.MondayFull),
ShortName = nameof(Strings.MondayShort),
Description = nameof(Strings.MondayDescription),
ResourceType = typeof(Strings)
)]
Monday,
[Display(ShortName = "Tue")]
Tuesday,
[Display]
Wednesday,
[Display(Name = "Thursday")]
Thursday,
[Display(Name = "Friday", ShortName = "Fri")]
Friday,
[Display(ShortName = "Sat", Description = "Almost the last day of the week")]
Saturday,
[Display(Description = "The last day of the week")]
Sunday
}By setting ResourceType and referencing a .NET resource class (like Strings above), the generator calls the resource manager to retrieve localized values for Name, ShortName, or Description. This simplifies translation of enum fields.
This will generate code on the following classes:
Additional Features
GetDisplayName()- Retrieves
DisplayAttribute.Name. IfResourceTypeis set, it attempts to get the localized text.
- Retrieves
GetDisplayShortName()- Returns
DisplayAttribute.ShortName, localized if aResourceTypeis provided.
- Returns
GetDescription()- Reads
DisplayAttribute.Description, also supporting localization viaResourceType.
- Reads
TryCreateFromDisplayName(),TryCreateFromDisplayShortName(),TryCreateFromDescription()- Methods in
<EnumName>Factorythat parse an input string to the matching enum member. They also factor in localized values when available.
- Methods in
When to Use
DisplayAttribute is ideal for presenting user-friendly text in UIs, logs, or exported data. By specifying a ResourceType, you have a convenient way to localize enum values, short names, and descriptions into multiple languages without duplicating code. This approach unites domain logic with customizable presentation.