tags:

views:

82

answers:

4

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?

+13  A: 

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.

Oded
Typically enums are used to convey some meaning. Nullable indicates absence of any value and more useful if the enum is coming from a database. Even in this case a special enum like "Unspecified" is a better option.
Pratik
+1  A: 

According to the documentation:

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

...

The default value of an enum E is the value produced by the expression (E)0.

There is also possibility to modify this default value:

enum PossibleOptions { Unspecified = 1, One, Two }

In this case Unspecified will no longer be the default value.

The only possible advantage that I can see of using a nullable enum is that the null value will not be dependent on the definition of the enumeration.

In my opinion you should decide which one to use depending on whether you need the semantics of default value or unassigned value.

Darin Dimitrov
A: 

The only reason (besides personal preference) to use a nullable enum is if you are using it both with and without being nullable.

By using a nullable enum you don't have the null value as one of the values. You can get the value from the nullable property, and use it somewhere else where the null value shouldn't be a possible value.

Guffa
A: 

I would choose the additional "unspecified" value of the enum. With a nullable value you make the assumption that it would occur to another developer to pass null. With a complete array of values, there's no assumption to make - every possible option is clear within that value set.

Superstringcheese