Get Enum Value Name - CSharp System.Reflection

CSharp examples for System.Reflection:Enum

Description

Get Enum Value Name

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;/* ww w  .  j  a  v a2 s . c om*/
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        public static string GetEnumValueName(this Type enumType, object enumVal)
        {
            var field = enumType.GetFields().Single(f => f.Name == Enum.GetName(enumType, enumVal));

            var enumMember = field.GetCustomAttribute<System.Runtime.Serialization.EnumMemberAttribute>();
            if (enumMember == null || enumMember.Value == null)
            {
                return Enum.GetName(enumType, enumVal);
            }

            return enumMember.Value;
        }
}

Related Tutorials