Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable enum or an additional element

Tags:

c#

.net

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?

like image 849
alwayslearning Avatar asked Aug 13 '10 11:08

alwayslearning


People also ask

Can we make enum nullable?

Enum types cannot be nullable.

How do you handle a nullable enum in C#?

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.

Can enum field be null?

An ENUM can also contain NULL and empty values.

Can we assign null to enum in Java?

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.


1 Answers

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.

like image 62
Oded Avatar answered Sep 21 '22 13:09

Oded