tags:

views:

566

answers:

3

If I have a class with an enum member, and I want to be able to represent situations where this member is not defied, which is it better:

A) Declare the member as nullable in the class using nullable types. E.g.:

public SomeEnum? myEnum;

B) Add a default, 'unknown' value to the enumeration. E.g.:

public enum SomeEnum {
    Unknown,
    SomeValueA,
    SomeValueB,
    SomeValueC,
}

I can't really see any major pros/cons either way. But perhaps one is preferrable over the other?

+4  A: 

Definitely use a nullable value type - that's what they're for. It explicitly states your intention. It also means you can use Enum.IsDefined (or the equivalent from Unconstrained Melody if you want generic type safety) to easily determine whether a particular value is a real value without worrying about the "fake" one too.

Jon Skeet
Interesting. Related: Why does FxCop complain about enumerations without a zero value (i.e. in enums that assign explicit values for each entry), suggesting a "None" entry with value 0? Doesn't it seem like adding an artificial "None" is a "fake" value like your answer states, therefore being an inferior solution? See: http://msdn.microsoft.com/en-us/library/ms182149(VS.80).aspx
Pwninstein
Perhaps the FxCop rule is older than nullable types?
Jon Skeet
Yeah, it's going back to my point about if you use a nullable then you get a sensible default, which is what that rule is trying to enforce.
Fiona Holder
Good explanation, just checked out the code for the Unconstrained Melody project, very interesting stuff. I wonder what could with combining the DelegateConstraint concept with linq expressions...
LorenVS
+2  A: 

If it's nullable, you'd get it as a default value, you'd get exceptions if you tried to use it when null (which is a good thing!)

Fiona Holder
+1  A: 

You just have to decide whether you need a value to represent unknown values, or you do need a way to represent absence of any value.

In the case of a need to represent unknown values, an extra enum-member sounds good as a solution.

In case of a need to represent absence of any value, make it nullable.

Have in mind, that there is nothing wrong with having both "unknown" enum-member and the enum itself being nullable at the same time.

HTH.

archimed7592