Consider the following Enum and a corrsponding nullable field of that type
enum PossibleOptions { One, Two }
PossibleOptions? option;
Alternatively I could declare the enum and the corresponding field as
enum PossibleOptions { Unspecified, One, Two }
PossibleOptions option;
This non-nullable field would be initialized to the first value i.e 'Unspecified' and I achieve the same result as a nullable ('Unspecified' would replace option.HasValue).
Why go for a Nullable then? Any performance gains or other advantages?
Enum types cannot be nullable.
c# enum variable set to nonthing That being said you can use the built in Nullable<T> class which wraps value types such that you can set them to null, check if it HasValue and get its actual Value. (Those are both methods on the Nullable<T> objects. Nullable<Color> color = null; //This will work.
An ENUM can also contain NULL and empty values.
If you want to represent null with an enum, then you'll have to explicit this by using a null object pattern manually with a NONE value and a custom implementation for prettyPrint() based on NONE value.
I know you are asking about reasons in favor of nullable enums, but personally I don't see any reason to use them.
An enum that has an "invalid" member is in my opinion a lot more readable and conveys meaning much more than a nullable.
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