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?
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 isushortitself. (Note that it’s not really “inheriting fromushort” even though it uses the same syntax – it’s really just saying “the underlying type isushort“.)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).Nameand getUInt16IMO.If you’re trying to determine the underlying type, you should use
Type.GetEnumUnderlyingType:EDIT: Just for completeness, if
MyEnumreally did inherit fromushort, you’d still be testing for type equality. As cdhowie says in the comments, if you wrote:that would still break into the debugger. You might want to look at
Type.IsAssignableFromfor situations where you really want to make that kind of comparison.