Partilhar via


Enumerations in the Common Type System 

An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying primitive type. An enumeration type has a name, an underlying type, and a set of fields. The underlying type must be one of the built-in signed or unsigned integer types (such as Byte, Int32, or UInt64). The fields are static literal fields, each of which represents a constant. The same value can be assigned to multiple fields. When this occurs, you must mark one of the values as the primary enumeration value for purposes of reflection and string conversion.

You can assign a value of the underlying type to an enumeration and vice versa (no cast is required by the runtime). You can create an instance of an enumeration and call the methods of System.Enum, as well as any methods defined on the enumeration's underlying type. However, some languages might not allow you to pass an enumeration as a parameter when an instance of the underlying type is required (or vice versa).

The following additional restrictions apply to enumerations:

  • They cannot define their own methods.

  • They cannot implement interfaces.

  • They cannot define properties or events.

  • An enumeration cannot be generic, unless it is generic solely because it is nested within a generic type. That is, an enumeration cannot have type parameters of its own.

    NoteNote

    Nested types (including enumerations) created with Visual Basic, C#, and C++ include the type parameters of all enclosing generic types, and are thus generic even if they do not have type parameters of their own. For more information, see "Nested Types" in MakeGenericType.

    It is possible to declare a generic enumeration in Microsoft intermediate language (MSIL) assembly language, but a TypeLoadException occurs if an attempt is made to use the enumeration.

The Flags attribute denotes a special kind of enumeration called a bit field. The runtime itself does not distinguish between traditional enumerations and bit fields, but your language might do so. When this distinction is made, bitwise operators can be used on bit fields, but not on enumerations, to generate unnamed values. Enumerations are generally used for lists of unique elements, such as days of the week, country or region names, and so on. Bit fields are generally used for lists of qualities or quantities that might occur in combination, such as Red And Big And Fast.

The following example shows how to use both bit fields and traditional enumerations.

Imports System
Imports System.Collections

' A traditional enumeration of some root vegetables.
Public Enum SomeRootVegetables
    HorseRadish
    Radish
    Turnip
End Enum 'SomeRootVegetables

' A bit field or flag enumeration of harvesting seasons.
<Flags()> Public Enum Seasons
   None = 0
   Summer = 1
   Autumn = 2
   Winter = 4
   Spring = 8
   All = Summer Or Autumn Or Winter Or Spring
End Enum 'Seasons

' Entry point.
Public Class EnumerationSample
    
    Public Shared Sub Main()
        ' Hash table of when vegetables are available.
        Dim AvailableIn As New Hashtable()
        
        AvailableIn(SomeRootVegetables.HorseRadish) = Seasons.All
        AvailableIn(SomeRootVegetables.Radish) = Seasons.Spring
        AvailableIn(SomeRootVegetables.Turnip) = Seasons.Spring Or _
            Seasons.Autumn
        
        ' Array of the seasons, using the enumeration.
        Dim MySeasons() As Seasons = {Seasons.Summer, Seasons.Autumn, _
            Seasons.Winter, Seasons.Spring}
        
        ' Print information of what vegetables are available each season.
        Dim i As Integer
        For i = 0 To MySeasons.Length - 1
            Console.WriteLine( _
                "The following root vegetables are harvested in " _
                & MySeasons(i).ToString("G") & ":")
            Dim e As DictionaryEntry
            For Each e In AvailableIn
                ' A bitwise comparison.
                If(CType(e.Value, Seasons) And MySeasons(i)) > 0 Then
                    Console.WriteLine("  " & _
                        CType(e.Key, SomeRootVegetables).ToString("G"))
                End If
            Next e
        Next i
    End Sub 'Main
End Class 'EnumerationSample
using System;
using System.Collections;

// A traditional enumeration of some root vegetables.
public enum SomeRootVegetables
{
    HorseRadish,
    Radish,
    Turnip
}

// A bit field or flag enumeration of harvesting seasons.
[Flags]
public enum Seasons
{
    None = 0,
    Summer = 1,
    Autumn = 2,
    Winter = 4,
    Spring = 8,
    All = Summer | Autumn | Winter | Spring
}

// Entry point.
public class EnumerationSample
{
    public static void Main()
    {
        // Hash table of when vegetables are available.
        Hashtable AvailableIn = new Hashtable();

        AvailableIn[SomeRootVegetables.HorseRadish] = Seasons.All;
        AvailableIn[SomeRootVegetables.Radish] = Seasons.Spring;
        AvailableIn[SomeRootVegetables.Turnip] = Seasons.Spring | 
            Seasons.Autumn;

        // Array of the seasons, using the enumeration.
        Seasons[] seasons = new Seasons[] { Seasons.Winter, Seasons.Spring, 
            Seasons.Summer, Seasons.Autumn };

        // Print information of what vegetables are available each season.
        for (int i = 0; i < seasons.Length; i++)
        {
            Console.WriteLine(
                "The following root vegetables are harvested in "
                + seasons[i].ToString("G") + ":");
            foreach (DictionaryEntry e in AvailableIn)
            {
                // A bitwise comparison.
                if (((Seasons)e.Value & seasons[i]) > 0)
                    Console.WriteLine("  " +
                        ((SomeRootVegetables)e.Key).ToString("G"));
            }
        }
    }
}

The output from this program is as follows.

The following root vegetables are harvested in Summer:
  HorseRadish
The following root vegetables are harvested in Autumn:
  Turnip
  HorseRadish
The following root vegetables are harvested in Winter:
  HorseRadish
The following root vegetables are harvested in Spring:
  Turnip
  Radish
  HorseRadish

See Also

Reference

System.ValueType
System.Enum

Concepts

Value Types in the Common Type System
.NET Framework Class Library Overview

Other Resources

Common Type System