开发者

Why do some people use "None" as enumeration member?

I noticed that some enumerations have "None" as a enumeration member.

For example what I mean

enum Mode
{
    Mode1 = 1,
    Mode2 = 2,
    Mode3 = 3,
    None = 4
}

Why do they use it ? In what cases solution with a none member is more preferable (less pre开发者_Go百科ferable) ?


None is important for [Flags] enums, and should have the value 0. Otherwise... questionable. A Nullable<Mode> would also suffice. But None may be demanded for their serialization or ORM layers (it might map to an expected string / int-value etc). Or it might just make the API simpler.


Logically None could be a valid choice (depends on the meaning of your enumeration) -> could have a separate branch in a switch case (arguably - not always a None option makes sence)

Regarding having a None option an a Nullable<Mode> variable: I would go for None for consistency: if you have 3 valid options and None is one of them, why treat it differently?

And if you choose or not to have a None option you should always have a enum value mapped as 0 (the default option). The link provided by Hans Kesting makes a good point about having a value mapped as 0:

The default value of an un-initialized enumeration, like other value types, is zero. A non-flags attributed enumeration should define a member with the value of zero so that the default value is a valid value of the enumeration. If appropriate, name the member 'None'. Otherwise, assign zero to the most commonly used member. Note that if the value of the first enumeration member is not set in the declaration, its value is zero by default.


It is required by a Code Analysis rule, see http://msdn.microsoft.com/en-us/library/ms182149(VS.100).aspx for the official reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜