ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetStringValue

If your enum member has attribute Display from System.ComponentModel.Annotations you can get this annotation value

Source

public static string GetStringValue(this Enum value)
{
    if (value == null)
    {
        return null;
    }

    var memberInfo = value.GetType().GetMember(value.ToString()).FirstOrDefault();

    return memberInfo?.GetCustomAttribute<DisplayAttribute>()?.GetName() ?? string.Empty;
}

Example

public enum Sample { 
[Display("ExampleValue")]
Value
}

public class Program {
 public void Main(){
  Console.WriteLine(Sample.Value.GetStringValue()); // prints ExampleValue
 }
}

Author: Skirtek

Submitted on: 2 apr. 2020

Language: csharp

Type: System.Enum

Views: 5022