How to display custom string for enum value in C#
By FoxLearn 10/29/2024 11:13:21 PM 270
In C#, you can display a custom string for enum values by using the Description attribute from the System.ComponentModel namespace.
For example:
using System.ComponentModel; public enum CardType { [Description("Standard Card")] StandardCard, [Description("Premium Card")] PremiumCard }
Create an extension method that uses reflection to get the DisplayAttribute
and returns the custom display name.
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; public static class EnumExtensions { public static string GetDisplayName(this Enum value) { var field = value.GetType().GetField(value.ToString()); var attribute = (DisplayAttribute)Attribute.GetCustomAttribute(field, typeof(DisplayAttribute)); return attribute?.Name ?? value.ToString(); // Fallback to enum name } }
You can now retrieve the display name directly from any enum instance.
var cardType = CardType.StandardCard; Console.WriteLine(cardType.GetDisplayName()); // Outputs: "Standard Card"
This simple syntax (enum.ToDisplayName()
) allows for easy access to custom display names defined in the DisplayAttribute
, making your code cleaner and more readable.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Stisla Admin Dashboard Template
11/18/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024
Portal HTML Bootstrap
11/14/2024