Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

Enums store special values. They make programs simpler. If you place constants directly where used, your C# program rapidly becomes complex and hard to change. Enums instead keep these magic constants in a distinct type—this improves code clarity and alleviates maintenance issues.
An enum type is a distinct value type that declares a set of named constants. Hejlsberg et al., p. 585
In this first example, we see an enum type that indicates the importance of something. As described by MSDN, an enum type 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.
Key point: Enums store constant values in the C# language. They can store magic constants.
Program that uses enums [C#]
using System;
class Program
{
enum Importance
{
None,
Trivial,
Regular,
Important,
Critical
};
static void Main()
{
// 1.
Importance value = Importance.Critical;
// 2.
if (value == Importance.Trivial)
{
Console.WriteLine("Not true");
}
else if (value == Importance.Critical)
{
Console.WriteLine("True");
}
}
}
Output
TrueDescription. We see a new variable with the identifier "value" is of the Importance type. It is initialized to Importance.Critical in part 1. At part 2, the variable is tested against other enum constants.

Enum usage tips. Enums can be used with IntelliSense in Visual Studio. If you type the above example, Visual Studio will guess the value you are comparing the enum value to. You can simply press tab and select the enum type you want. This is an advantage to using enum types.
Next, we examine what enums looks like in the Visual Studio 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.
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
BoldWhat 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.

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.
Tip: 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
Dog
HiddenNotes. 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.
Enum ToString MethodTip: Many of the example programs on this page use short, letter-based identifiers (such as b1, v1) for enum variables. These are not ideal. It would be better to use more descriptive words, such as "animal" or "visibility".

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.
Enum.Parse Enum.TryParse Typeof OperatorGet names. It is possible to get the name for any value of a specified enum. You can also get all the string representations of the enum values at once: this is done with the GetNames method. This can streamline some code that must print out enums.
Enum.GetName Enum.GetNames
Format enums. It is possible to format the values stored in enums in different ways: you can display an integer representation, or a hex representation. The article shown here provides some further explanations.
Enum.FormatThe above samples show the if statement used with enums. However, switch in the C# language is sometimes compiled to more efficient IL. Here we want to use switch on an enum variable.
Switch EnumProgram 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
TrueImportant 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.

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 with default value of None [C#]
enum E
{
None,
A,
B,
C
};
FxCop note. Microsoft's FxCop analysis tool will tell you that "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."
MSDN referenceNext, let's look at how you can use enumerated types with data structures such as the Stack collection in the .NET Framework. One usage I have 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.
Program that uses Stack with enums [C#]
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.
}
}
Result
(The stack has two enums added and one removed.)Overview. 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.
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.
Stack Collection![Attribute [Flags] syntax](http://d1g3ybcl16zbb8.cloudfront.net/attribute.png)
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.
Enum Flags Attribute
You can use enums as keys to arrays by converting them to integers. This approach can be useful for some kinds of tables or data structures in your C# programs.
Enum Array ExampleEach enum has an underlying type: this is a value type that the actual data is stored in. The GetUnderlyingType method on the Enum type provides a way to programmatically access this type.
Enum.GetUnderlyingType Method
Will enums impact the performance of your C# programs? In this article, we look at the intermediate language of enum types to determine this. Enums are loaded in a different way from regular fields.
Enum Performance (IL)
In this tutorial, we saw how you can use enums in your C# programs to improve code clarity and reduce the probability of invalid values. We can use enums to represent constant values such as integers in a consistent way that is checked by the compiler. It's a good idea to avoid magic constants or numbers with self-documenting enum types.