C# int, Int32 and enums
If int
is synonymous to Int32
why does
enum MyEnum : Int32
{
Value = 1
}
...not compile? Where as
enum MyEnum : int
{
Value = 1
}
will, even though hovering the cursor over the int word will display struct System.Int32?
Solution 1:
The underlying type is indeed the same, but the compiler depends on the type to be as the exact alias. This is a compilation error based on parsing. I took a look at C# grammar specification and the underlying types defined there as tokens based on the alias (e.g. 'int', 'unit'... etc.). The parser expects specific strings from the integral-types grammar rule.
The error is a parsing error even though both enum Enum : int
means the same as enum Enum : Int32
.
I don't know the reason for forcing this limit to parsing step, but I can try guessing: Since Int32 is not a keyword it might refer to something other the actual int struct. If the parser has to know the type in order to build different AST for each base type then it cannot depend on token which is not a keyword.
Even though the C# specification defines the int keyword as explicit alias System.Int32, it's still a problem to get this information about the explicit type (Int32) during parsing step since it requires a lot of context information which cannot be inferred at this step.
Solution 2:
A familiar curiosity... the language spec states (14.1):
An enum declaration may explicitly declare an underlying type of byte, sbyte, short, ushort, int, uint, long or ulong. Note that char cannot be used as an underlying type. An enum declaration that does not explicitly declare an underlying type has an underlying type of int.
But since int
is generally just an alias for System.Int32
it isn't unreasonable to think either might work... but indeed it doesn't. It isn't generally a big problem, but intriguing none the less.