WurstScript
WurstScript copied to clipboard
Enums Implicitly Converts to Int when Compared to Null
Let's use the following enum
as an example:
public enum AreaType
WOODLAND
SNOWY
The compiler will associate 0
with WOODLAND
and 1
with SNOWY
.
The compiler complains if we try to compare an enum
with an integer
. This is a good thing. Take for instance:
let isWoodland = AreaType.WOODLAND == 0
The above gives the error Cannot compare types AreaType with integer-literal
. Exactly what we want.
Unfortunately, comparison between enum
and null
works. This produces unexpected results:
let isWoodland = AreaType.WOODLAND == null
isWoodland
will be assigned true
since null
is coalesced into 0
(which coincides with the integer representation of WOODLAND
). This leads to subtle bugs. Note that you can also do meaningless stuff like AreaType areaType = null
.
I think comparison between enum
and null
should give a compiler error instead.
I'm not sure if AreaType areaType = null
is meaningless, but the better variant would probably to define a "null" member of the enum to use instead.
I'm not sure if AreaType areaType = null is meaningless, ...
The semantics could be sound. The current implementation, however, is not sound. The current implementation does not properly handle the comparison against null, which leads to bad code gen (it's a bug).
I suggest, that we either:
- Issue a compile-time error if comparing an
enum
tonull
. - Implicitly add a hidden
null
member to allenum
s that is used for comparisons againstnull
.
Personally, I favor the first approach but I'd be happy with either solution.
...but the better variant would probably to define a "null" member of the enum to use instead.
This is normally what I do when I need a none
/null
/undefined
/unassigned
value for the enum in Wurst and other languages.