/// <summary> /// Retrieves the name of the constant in the specified enumeration that has the specified value. /// </summary> /// <param name="enumType">An enumeration type.</param> /// <param name="value">The value of a particular enumerated constant in terms of its underlying type.</param> /// <returns> A string containing the name of the enumerated constant in enumType whose value is value, or null if no such constant is found.</returns> /// <exception cref="ArgumentException"> enumType is not an System.Enum. -or- value is neither of type enumType nor does it have the same underlying type as enumType.</exception> public static string GetName(Type enumType, object value) { if (enumType == null) { throw new ArgumentNullException(nameof(enumType)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Type valueType = value.GetType(); if (!valueType.IsEnum && !Type2.IsIntegerNumber(valueType)) { throw new ArgumentException("The specified value should be enum base or an integer number", nameof(value)); } int length; bool isFlags; Type underlyingType; var valuesAndNames = GetValuesAndNames(enumType, out length, out isFlags, out underlyingType); object numValue = Convert.ChangeType(value, underlyingType, null); //cycle through the enum values foreach (var item in valuesAndNames) { //if value matches return the name if (numValue.Equals(item.ValueAsNumber)) { return(item.Name); } } //if there is no match return null return(null); }
private static string InternalValuesFormat(Type enumType, object value) { int length; bool isFlags; Type underlyingType; var valuesAndNames = GetValuesAndNames(enumType, out length, out isFlags, out underlyingType) .OrderBy(a => a.ValueAsNumber) .ToArray(); if (valuesAndNames.Length == 0) { return(value.ToString()); } if (Type2.IsSignedNumber(underlyingType)) { return(InternalSignedValuesFormat(enumType, value, valuesAndNames)); } else { return(InternalUnsignedValuesFormat(enumType, value, valuesAndNames)); } }