Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

C# Enums: Nullable or 'Unknown' Value?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...