I am defining a custom typedef Elements as follows....
typedef enum {
Ar,
Cl,
F,
He,
H,
Kr,
Ne,
N,
O,
Rn,
Xe
} Element;
I want to check a variable of type Element has not been set (essentially just check for a NULL value). As far as I can tell the only way to do this is to add an extra line
.... {
unknown = 0,
Ar,
F,
...etc
Am I right or is there a more elegant way to do this?
Enum types cannot be nullable.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
All enum types are value types and the different members are also derived from member types (the allowed types are byte , sbyte , short , ushort , int , uint , long , or ulong - as documented). This means that members of an enumeration cannot be null .
Enumerations are similar to classes and, you can have variables, methods, and constructors within them.
Yes, you should include an "unknown" value. Basically an enum
is just an int
. If you don't define any constants in the declarations (as in your first code sample) the first option will be set to 0
and the default value.
An alternative might be to set the first option to 1
. This way the value 0
won't be defined and you can check for that manually.
typedef enum {
Ar = 1,
Cl,
F,
He,
H,
Kr,
Ne,
N,
O,
Rn,
Xe
} Element;
if (myElement) { // same as if (myElement != 0)
// Defined
} else {
// Undefined
}
But I would opt for an explicitly defined "unknown" value instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With