public static string Format(Type enumType, object value, string format)
{
if (enumType == null)
{
throw new ArgumentNullException(nameof(enumType));
}
if (!enumType.IsEnum)
{
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (format == null)
{
throw new ArgumentNullException(nameof(format));
}
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
{
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
}
// Check if both of them are of the same type
Type valueType = value.GetType();
Type underlyingType = GetUnderlyingType(enumType);
// If the value is an Enum then we need to extract the underlying value from it
if (valueType.IsEnum)
{
if (!valueType.IsEquivalentTo(enumType))
{
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), enumType.ToString()));
}
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
return(((Enum)value).ToString(format));
}
// The value must be of the same type as the Underlying type of the Enum
else if (valueType != underlyingType)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString()));
}
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'G' || formatCh == 'g')
{
return(GetEnumName(rtType, ToUInt64(value)) ?? value.ToString());
}
if (formatCh == 'D' || formatCh == 'd')
{
return(value.ToString());
}
if (formatCh == 'X' || formatCh == 'x')
{
return(InternalFormattedHexString(value));
}
if (formatCh == 'F' || formatCh == 'f')
{
return(Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString());
}
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}