Reputation: 38714
I have sometimes seen enum
s like this:
public enum Color {
None, Black, Red, Blue
}
with code like:
Color color;
...
if (color == Color.None) ...
I would prefer using a nullable enum and code it like this:
public enum Color {
Black, Red, Blue
}
...
Color? color;
...
if (color == null) ...
Which style is preferred?
Upvotes: 3
Views: 2868
Reputation: 93978
Personally I would avoid something like None
as a Color. None obviously is not a color, and it is therefore semantically not correct. Whenever that happens you run into trouble.
E.g. try and imagine a Set
of possible colors. [ White, Black, Red ]
makes sense, but obviously [ White, Black, None ]
doesn't.
null
would be preferable, although you could also try and work around the issue, e.g. a isPresent()
method or something similar.
Upvotes: 2
Reputation:
If it's valid for whatever object you're setting the color of to not have a color I think you should have None as an option, otherwise leave it off.
Upvotes: 0
Reputation: 1500735
As ever, it depends.
For a [Flags]
enum, a None
value is almost always a good idea, as "none of these options" is a useful concept. For a non-[Flags]
enum, I wouldn't usually include a None
value unless it was obviously conceptually useful.
That said, the enum guidelines as part of "Design Guidelines for Developing Class Libraries" include:
Do provide a value of zero on simple enumerations.
If possible, name this value None. If None is not appropriate, assign the value zero to the most commonly used value (the default).
... although the examples don't include None
, and many enums in the .NET framework don't have None
values either...
As for whether you should use a nullable enum or not - it really depends on the situation. I would use a Color?
variable for "there may be a Color
value, or there may not be" because None
really isn't a sensible colour. Not having None
means that Enum.IsDefined(typeof(Color))
is more useful, IMO. Why would enums be different to any other non-nullable value type? You wouldn't normally use 0 for "we don't have any information" - you'd use an int?
instead. I'd suggest treating enums in a manner consistent with how you'd treat int
.
(Having said all of this, I see that I include None
as a value in IsoDayOfWeek
in Noda Time, which I find surprising, looking at it right now.)
Upvotes: 13
Reputation: 25705
None
over null
. None
makes it more than obvious to guess. And you can use it like this: colorObject.None
. But this is subjective and based on tastes.
There is no color
called "null" but there can be a no-color
(transparent?).
Upvotes: 0
Reputation: 150253
It depends on what is the meaning you want to give to None
.
null
is unknown, null can be any color or with no color, but we don't know the color.
While None sounds as the color is known to be: absent of a color.
So..pick the right thing for you application.
Upvotes: 1