Reputation: 170
If I declare an enum inheriting from ushort like this:
public enum MyEnum : ushort { A = 0, B = 1 };
and then check its type like this:
if(typeof(MyEnum) != typeof(ushort))
System.Diagnostics.Debugger.Break();
The breakpoint is called. Why is this happening?
Upvotes: 2
Views: 1010
Reputation: 1499780
It's called because they're not the same type! One is an enum type with an underlying value of type ushort
, and the other is ushort
itself. (Note that it's not really "inheriting from ushort
" even though it uses the same syntax - it's really just saying "the underlying type is ushort
".)
Why would you expect them to be the same type? If they were actually the same type, you'd lose a lot of the type safety of enums.
It would be very odd to print typeof(MyEnum).Name
and get UInt16
IMO.
If you're trying to determine the underlying type, you should use Type.GetEnumUnderlyingType
:
if (typeof(MyEnum).GetEnumUnderlyingType() == typeof(ushort))
{
// Yup, the underlying type is ushort
}
EDIT: Just for completeness, if MyEnum
really did inherit from ushort
, you'd still be testing for type equality. As cdhowie says in the comments, if you wrote:
if (typeof(string) != typeof(object))
{
Debugger.Break();
}
that would still break into the debugger. You might want to look at Type.IsAssignableFrom
for situations where you really want to make that kind of comparison.
Upvotes: 8