Reputation: 46128
Enums are generally used to define the state of a particular property of a class, say in an object model of some sort. For some of these properties, the state 'this property is not set' is valid.
In these situations, should I use a zero None
enum value, or make the property type nullable?
public MyEnum Property { get; set; }
public enum MyEnum {
None = 0,
Value1,
Value2
}
or
public MyEnum? Property { get; set; }
public enum MyEnum {
Value1,
Value2
}
Upvotes: 0
Views: 1499
Reputation: 4867
Another option is to set the first value to 1, since it will be initally 0.
public enum MyEnum {
Value1 = 1,
Value2
}
I think both of your situations are acceptable! It will depend upon your situation. When working with a user interface your first example with the 'None' value will probbaly be easier to use. However, the Nullable gives more information about how the variable should be used.
Upvotes: 0
Reputation: 38778
I would use the "None" value instead of a nullable enum. If nothing else, to me if(Property == MyEnum.None)
is a lot more readable than if(Property == null)
.
Upvotes: 0
Reputation: 62057
It's hard to answer this conclusively, a lot of factors in your app will influence this. I tend to just define the enum value to 0, but not specify a zero value in the enum.
enum Foo
{
A = 1,
B = 2
}
...
Foo myFoo = (Foo)0;
This gives the benefit of a sentinel value, without polluting the enum.
Upvotes: 0
Reputation: 499152
Use MyEnum.None
- it is much more expressive, or even MyEnum.Invalid
to convey meaning.
You can also set it to other values than 0 - since it is based on int, you can set it to be -1 and the first valid value to 1:
public enum MyEnum {
InvalidValue = -1,
Value1 = 1,
Value2
}
In your code you can easily check for this value being passed in and throw a descriptive exception.
A nullable enum type is not expected and less expressive. It requires users of you code to be aware of this and check for nulls.
Upvotes: 6