#203 – It’s Good Practice to Always Have a 0-Valued Enumeration Constant

We saw earlier that you can declare any values you like for an enum type’s constants.

public enum Mood {
    Crabby = -5,
    Happy = 5,
    Petulant = -2,
    Elated = 10};

Clearly we can declare an enum type that has no constant that maps to the value of 0.

We saw earlier, however, that fields in a reference type are zeroed out when an instance of that object is constructed.  This can lead to having an enumerated field/property that has a 0 value but no matching constant in the enumerated type.

            Person p = new Person("Lillian", "Gish");

            Mood theMood = Mood.Happy;
            Console.WriteLine(theMood);    // Happy

            theMood = p.PersonMood;
            Console.WriteLine(theMood);    // 0   (unable to map to a constant)

This is allowed, since the enumerated value can be any integer.  But it’s better practice to always define a 0-valued constant.

    public enum Mood
    {
        NONE = 0,
        Crabby = -5,
        Happy = 5,
        Petulant = -2,
        Elated = 10
    };
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #203 – It’s Good Practice to Always Have a 0-Valued Enumeration Constant

  1. Naraayanan says:

    Nice , Please upload class file also.

  2. zzfima says:

    Hi. Probably, good if You will add info, that You are talking about value types in sentence “…that fields in a reference type are zeroed out when…”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: