BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Constants and Enumerations

The forty-eighth part of the C# Fundamentals tutorial examines the use of constants and enumerations. These provide two methods of describing non-changing values using descriptive words rather than "magic numbers" to improve code readability.

Specifying The List Values

In many cases you will want enumeration values to begin with an integer value that is non-zero. You may even wish to individually specify each value for the list. You can do this by assigning a value to any of the listed items using a standard assignment operator (=). If you miss a value for any item in the list, it is automatically assigned a value one greater than the previous item.

class Program
{
    enum IssueStatus
    {
        New = 1,
        Open,
        Closed,
        Cancelled = -1
    }

    static void Main(string[] args)
    {
        Console.WriteLine((int)IssueStatus.New);            // Outputs "1"
        Console.WriteLine((int)IssueStatus.Open);           // Outputs "2"
        Console.WriteLine((int)IssueStatus.Closed);         // Outputs "3"
        Console.WriteLine((int)IssueStatus.Cancelled);      // Outputs "-1"
    }
}

NB: The compiler will allow you to define multiple items with the same integer value. This is inadvisable as the results can be unpredictable.

Changing the Enumeration Base Type

Normally when an enumeration is declared, every constant in the list is a 32-bit integer, or int. This can be overridden to any other integer type except for char by adding a colon (:) and the alternative type after the enumeration's name.

enum IssueStatus : short
{
    New = 1,
    Open,
    Closed,
    Cancelled = -1
}
16 August 2007