If I have a class with an enum member and I want to be able to represent situations where this member is not defined, 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 preferable over the other?
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.