public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
if (!(enumType is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
if (!enumType.IsEnum)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
if (value == null)
throw new ArgumentNullException("value");
// Check if both of them are of the same type
Type valueType = value.GetType();
if (!(valueType is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "valueType");
Type underlyingType = GetUnderlyingType(enumType);
// If the value is an Enum then we need to extract the underlying value from it
if (valueType.IsEnum)
{
Type valueUnderlyingType = GetUnderlyingType(valueType);
if (valueType != enumType)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType"), valueType.ToString(), enumType.ToString()));
valueType = valueUnderlyingType;
}
else
// The value must be of the same type as the Underlying type of the Enum
if ((valueType != underlyingType) && (valueType != stringType))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Arg_EnumUnderlyingTypeAndObjectMustBeSameType"), valueType.ToString(), underlyingType.ToString()));
}
// If String is passed in
if (valueType == stringType)
{
// Get all of the Fields
String[] names = GetHashEntry(enumType).names;
for (int i = 0; i < names.Length; i++)
if (names[i].Equals((string)value))
return true;
return false;
}
ulong[] values = GetHashEntry(enumType).values;
// Look at the 8 possible enum base classes
if (valueType == intType || valueType == typeof(short) || valueType == typeof(ushort) || valueType == typeof(byte) || valueType == typeof(sbyte) || valueType == typeof(uint) || valueType == typeof(long) || valueType == typeof(ulong))
{
ulong val = ToUInt64(value);
return (BinarySearch(values, val) >= 0);
}
BCLDebug.Assert(false, "Unknown enum type");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}