C# Enum Tips and Examples

by Sam Allen - Updated January 26, 2010

You want to use enum values in your program to improve code clarity and make it easier to maintain. Enums provide better error-checking and compiler warnings. They store constants and important values. This document contains lots of examples and links about enums, using the C# programming language.

Enums store constant values in the C# language.
... They can store magic constants.            
... See the examples for tips on using them.   

Using enum types

First, we will look at MSDN's description and a simple example. Microsoft defines the enum keyword as something that is a "distinct type consisting of a set of named constants called the enumerator list." You will use enum when you want readable code that uses constants.

=== Example program that uses enums (C#) ===

using System;

class Program
{
    enum Importance
    {
        None,
        Trivial,
        Regular,
        Important,
        Critical
    };

    static void Main()
    {
        // 1.
        Importance i1 = Importance.Critical;

        // 2.
        if (i1 == Importance.Trivial)
        {
            Console.WriteLine("Not true");
        }
        else if (i1 == Importance.Critical)
        {
            Console.WriteLine("True");
        }
    }
}

=== Output of the program ===

True

Overview. We see a new variable called i1 is of the Importance type. It is initialized to Critical in part 1. At part 2, the value is tested against other enum constants.

Enum usage tips. Enums and IntelliSense: If you type the above example, Visual Studio will guess the value you are comparing the enum i1 to. You can simply press tab and select the enum type you want. This is an advantage.

Using enums in debugger

Here we examine what enums looks like in the Visual Studio 2008 debugger. We see that enums are strongly typed and you cannot assign them to just any value. The code example below is what we see in the debugger.

=== Example program that uses enums (C#) ===

using System;

class Program
{
    enum E
    {
        None,
        BoldTag,
        ItalicsTag,
        HyperlinkTag,
    };

    static void Main()
    {
        // A.
        // These values are enum E types.
        E en1 = E.BoldTag;
        E en2 = E.ItalicsTag;

        if (en1 == E.BoldTag)
        {
            // Will be printed.
            Console.WriteLine("Bold");
        }
        if (en1 == E.HyperlinkTag)
        {
            // Won't be printed.
            Console.WriteLine("Not true");
        }
    }
}

=== Output of the program ===

Bold

What the debugger displays. The debugger shows that en1 and en2 above are types of the enum Program.E. They are not integers, although internally this is how they are stored.

Enums in the Visual Studio debugger

Getting string values from enum

Here we see how you can convert your enums to strings for display on the Console. Enum values always have a name, such as E.None, E.BoldTag, or E.ItalicsTag. These are custom and you can specify any one you want within the enum declaration. Fortunately, you can access these strings in your program.

How to display strings from enums. To print out the enum values, you can call ToString() on the enum variable in your program. Alternatively, another method such as WriteLine can call the ToString() method automatically.

=== Program that writes enums (C#) ===

using System;

class Program
{
    static void Main()
    {
        // A.
        // Two enum variables:
        B b1 = B.Dog;
        V v1 = V.Hidden;

        // B.
        // Print out their values:
        Console.WriteLine(b1);
        Console.WriteLine(v1);
    }

    enum V
    {
        None,
        Hidden = 2,
        Visible = 4
    };

    enum B
    {
        None,
        Cat = 1,
        Dog = 2
    };
}

=== Output of the program ===

Dog
Hidden

Notes. Remember that Console will call the ToString() method on all types passed to it. This is how the string representation of the enums is found. Internally, the ToString virtual method will invoke methods that use reflection to acquire the string representation of the enumerated constant. There is more information about enum ToString calls on this site.

(See Enum String Method.)

Converting string to enum

Sometimes you have a string value that you want to convert to an equivalent enum. This could happen when you are accepting user input and want to put the input into your objects. The language provides a good way to convert strings to enums. You will use the Enum static class and the Parse method on it. The tricky part is using typeof and casting.

(See Enum.Parse Method Usage.)

Enum switch

The above samples show the if statement used with enums. However, switch in C# is sometimes compiled to more efficient IL. Here we want to use switch on an enum variable.

(See Switch Enum and Int.)

=== Example program that uses switch enums (C#) ===

using System;

class Program
{
    static void Main()
    {
        // 1.
        // Test enum with switch method.
        G e1 = G.None;
        if (IsFormat(e1))
        {
            // Won't succeed.
            // G.None is not a format value.
            Console.WriteLine("Error");
        }

        // 2.
        // Test another enum with switch.
        G e2 = G.ItalicsFormat;
        if (IsFormat(e2))
        {
            // Will succeed.
            // G.ItalicsFormat is a format value.
            Console.WriteLine("True");
        }
    }

    enum G
    {
        None,
        BoldFormat,    // Is a format value.
        ItalicsFormat, // Is a format value.
        Hyperlink      // Not a format value.
    };

    /// <summary>
    /// Returns true if the G enum value is a format value.
    /// </summary>
    public static bool IsFormat(G e)
    {
        switch (e)
        {
            case G.BoldFormat:
            case G.ItalicsFormat:
                {
                    // These two values are format values.
                    return true;
                }
            default:
                {
                    // The argument is not a format value.
                    return false;
                }
        }
    }
}

=== Output of the program ===

True

Important points. Some points are that IsFormat() above works as a filter that tells us something about sets of enum values. We can separate the logic here instead of repeating ourselves.

Using default value of 0

Here we mention that integers in the C# programming language are always initialized to zero when they are fields of a class. When you have an enum field, it will also be initialized to zero. To make enums valid, always use the default value of zero. This way, you can test for the default value of fields. Sometimes this isn't important, but it is useful for verifying correctness.

enum E
{
    None,
    A,
    B,
    C
};

Note on FxCop. What FxCop says: Microsoft's analysis tool will tell you "Enums should have zero value." [EnumsShouldHaveZeroValue, CA1008] You 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'.

(Visit msdn.microsoft.com.)

Enum collections

Here we look at how you can use enumerated types with data structures such as the Stack collection in the .NET Framework. One usage the author has had for enums is with Stack and keeping the current value on the top. Instead of Stack, you can use a List or Dictionary as well.

using System.Collections.Generic;

class Program
{
    static void Main()
    {
        M();
    }

    enum E
    {
        None,         // integer value = 0
        BoldTag,      // 1
        ItalicsTag,   // 2
        HyperlinkTag, // 3
    };

    static public void M()
    {
        // A.
        // Stack of enums.
        Stack<E> stack = new Stack<E>();

        // B.
        // Add enum values to the Stack.
        stack.Push(E.BoldTag);    // Add bold
        stack.Push(E.ItalicsTag); // Add italics

        // C.
        // Get the top enum value.
        E thisTag = stack.Pop(); // Get top tag.
    }
}

Overview of program text. It uses an enum E. The name E here is custom and can be anything. The enum keyword is important. We do not assign any specific numbers to the enum values. When you don't provide numbers, they start at zero and are incremented.

Description of the Stack logic. In part A, the Stack here can only have E values added to it. This enables type checking and validation. You might use List or Dictionary instead. In part C, we get the top E value. Here we get an E value that is on the top of the stack. This is E.ItalicsTag.

(See Stack Usage, Methods and Tips.)

[Flags] attribute

The language also allows you to specify a special Flags attribute on your enum, enabling it to be used as a bitfield. You can use combinations of enum values this way, but it is more limited in some situations.

(See Enum Flags Attribute Use.)

Summary

In this tutorial, we saw how you can use enums to improve code clarity and reduce the probability of invalid values, using the C# programming language. Use them to improve how you can display integers. Avoid "magic constants" or numbers with enums. Enums are self-documenting.

(Do not copy this page.)

Dot Net Perls | Search
Enums | Enum Flags Attribute Use | Enum String Method | Enum.Parse Method Usage | Environment.SpecialFolder | Switch Enum and Int
C# | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method | File.Replace Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen