4 out of 9 rated this helpful Rate this topic

Enum Class

Updated: June 2010

Provides the base class for enumerations.

System.Object
  System.ValueType
    System.Enum

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Enum : ValueType, 
	IComparable, IFormattable, IConvertible

The Enum type exposes the following members.

  Name Description
Protected method Supported by the XNA Framework Supported by Portable Class Library Enum Initializes a new instance of the Enum class.
Top
  Name Description
Public method Supported by the XNA Framework CompareTo Compares this instance to a specified object and returns an indication of their relative values.
Public method Supported by the XNA Framework Supported by Portable Class Library Equals Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).)
Protected method Supported by the XNA Framework Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Static member Format Converts the specified value of a specified enumerated type to its equivalent string representation according to the specified format.
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCode Returns the hash code for the value of this instance. (Overrides ValueType.GetHashCode.)
Public method Static member Supported by Portable Class Library GetName Retrieves the name of the constant in the specified enumeration that has the specified value.
Public method Static member GetNames Retrieves an array of the names of the constants in a specified enumeration.
Public method Supported by the XNA Framework Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Supported by the XNA Framework GetTypeCode Returns the underlying TypeCode for this instance.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library GetUnderlyingType Returns the underlying type of the specified enumeration.
Public method Static member GetValues Retrieves an array of the values of the constants in a specified enumeration.
Public method HasFlag Determines whether one or more bit fields are set in the current instance.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library IsDefined Indicates whether a constant with a specified value exists in a specified enumeration.
Protected method Supported by the XNA Framework Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Static member Parse(Type, String) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Parse(Type, String, Boolean) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-insensitive.
Public method Static member ToObject(Type, Byte) Converts the specified 8-bit unsigned integer to an enumeration member.
Public method Static member ToObject(Type, Int16) Converts the specified 16-bit signed integer to an enumeration member.
Public method Static member ToObject(Type, Int32) Converts the specified 32-bit signed integer to an enumeration member.
Public method Static member ToObject(Type, Int64) Converts the specified 64-bit signed integer to an enumeration member.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library ToObject(Type, Object) Converts the specified object with an integer value to an enumeration member.
Public method Static member ToObject(Type, SByte) Converts the specified 8-bit signed integer value to an enumeration member.
Public method Static member ToObject(Type, UInt16) Converts the specified 16-bit unsigned integer value to an enumeration member.
Public method Static member ToObject(Type, UInt32) Converts the specified 32-bit unsigned integer value to an enumeration member.
Public method Static member ToObject(Type, UInt64) Converts the specified 64-bit unsigned integer value to an enumeration member.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString Converts the value of this instance to its equivalent string representation. (Overrides ValueType.ToString.)
Public method Supported by the XNA Framework ToString(IFormatProvider) Obsolete. This method overload is obsolete; use Enum.ToString.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString(String) Converts the value of this instance to its equivalent string representation using the specified format.
Public method Supported by the XNA Framework ToString(String, IFormatProvider) Obsolete. This method overload is obsolete; use Enum.ToString(String).
Public method Static member TryParse(Of TEnum)(String, TEnum) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.
Public method Static member TryParse(Of TEnum)(String, Boolean, TEnum) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.
Top
  Name Description
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToBoolean Infrastructure. Converts the current value to a Boolean value based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToByte Infrastructure. Converts the current value to an 8-bit unsigned integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToChar Infrastructure. Converts the current value to a Unicode character based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToDateTime Infrastructure. Converts the current value to a DateTime based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToDecimal Infrastructure. Converts the current value to a Decimal based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToDouble Infrastructure. Converts the current value to a double-precision floating point number based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToInt16 Infrastructure. Converts the current value to a 16-bit signed integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToInt32 Infrastructure. Converts the current value to a 32-bit signed integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToInt64 Infrastructure. Converts the current value to a 64-bit signed integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToSByte Infrastructure. Converts the current value to an 8-bit signed integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToSingle Infrastructure. Converts the current value to a single-precision floating-point number based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToType Infrastructure. Converts the current value to a specified type based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToUInt16 Infrastructure. Converts the current value to a 16-bit unsigned integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToUInt32 Infrastructure. Converts the current value to a 32-bit unsigned integer based on the underlying type.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertible.ToUInt64 Infrastructure. Converts the current value to a 64-bit unsigned integer based on the underlying type.
Explicit interface implemetation Private method Supported by Portable Class Library IFormattable.ToString Infrastructure. This method overload is obsolete; use Enum.ToString(String).
Top

An enumeration is a set of named constants whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Enum is the base class for all enumerations in the .NET Framework.

Enum provides methods for comparing instances of this class, converting the value of an instance to its string representation, converting the string representation of a number to an instance of this class, and creating an instance of a specified enumeration and value.

You can also treat an enumeration as a bit field. For more information, see the Non-Exclusive Members and the Flags Attribute section and the FlagsAttribute topic.

Creating an Enumeration Type

Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values. The following example illustrates the syntax used by C# and Visual Basic to define an enumeration. It creates an enumeration named ArrivalStatus that has three members: ArrivalStatus.Early, ArrivalStatus.OnTime, and ArrivalStatus.Late. Note that in both cases, the enumeration does not explicitly inherit from Enum; the inheritance relationship is handled implicitly by the compiler.


public enum ArrivalStatus { Late=-1, OnTime=0, Early=1 };


Caution note Caution

You should never create an enumeration type whose underlying type is non-integral. Although you can create such an enumeration type by using reflection, method calls that use the resulting type are unreliable and may also throw additional exceptions.

Instantiating an Enumeration Type

You can instantiate an enumeration type just as you instantiate any other value type: by declaring a variable and assigning one of the enumeration's constants to it. The following example instantiates an ArrivalStatus whose value is ArrivalStatus.OnTime.


public class Example
{
   public static void Main()
   {
      ArrivalStatus status = ArrivalStatus.OnTime;
      Console.WriteLine("Arrival Status: {0} ({0:D})", status);
   }
}
// The example displays the following output:
//       Arrival Status: OnTime (0)


You can also instantiate an enumeration value in the following ways:

  • By using a particular programming language's features to cast (as in C#) or convert (as in Visual Basic) an integer value to an enumeration value. The following example creates an ArrivalStatus object whose value is ArrivalStatus.Early in this way.

    
    ArrivalStatus status2 = (ArrivalStatus) 1;
    Console.WriteLine("Arrival Status: {0} ({0:D})", status2);
    // The example displays the following output:
    //       Arrival Status: Early (1)
    
    
    
  • By calling its implicit default constructor. As the following example shows, in this case the underlying value of the enumeration instance is 0. However, this is not necessarily the value of a valid constant in the enumeration.

    
    ArrivalStatus status1 = new ArrivalStatus();
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1);
    // The example displays the following output:
    //       Arrival Status: OnTime (0)
    
    
    
  • By calling the Parse or TryParse method to parse a string that contains the name of a constant in the enumeration. For more information, see the Parsing Enumeration Values section.

  • By calling the ToObject method to convert an integral value to an enumeration type. For more information, see the Performing Conversions section.

Enumeration Best Practices

We recommend that you use the following best practices when you define enumeration types:

  • If you have not defined an enumeration member whose value is 0, consider creating a None enumerated constant. By default, the memory used for the enumeration is initialized to zero by the common language runtime. Consequently, if you do not define a constant whose value is zero, the enumeration will contain an illegal value when it is created.

  • If there is an obvious default case that your application has to represent, consider using an enumerated constant whose value is zero to represent it. If there is no default case, consider using an enumerated constant whose value is zero to specify the case that is not represented by any of the other enumerated constants.

  • Do not specify enumerated constants that are reserved for future use.

  • When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.

Additional best practices for enumeration types whose constants are bit fields are listed in the Non-Exclusive Members and the Flags Attribute section.

Performing Operations with Enumerations

You cannot define new methods when you are creating an enumeration. However, an enumeration type inherits a complete set of static and instance methods from the Enum class. The following sections survey most of these methods, in addition to several other methods that are commonly used when working with enumeration values.

Performing Conversions

You can convert between an enumeration member and its underlying type by using a casting (in C#) or conversion (in Visual Basic) operator. The following example uses casing or conversion operators to perform conversions both from an integer to an enumeration value and from an enumeration value to an integer.


int value3 = 2;
ArrivalStatus status3 = (ArrivalStatus) value3;

int value4 = (int) status3;


The Enum class also includes a ToObject method that converts a value of any integral type to an enumeration value. The following example uses the ToObject method to convert an Int32 to an ArrivalStatus value. Note that, because the ToObject returns a value of type Object, the use of a casting or conversion operator may still be necessary to case the object to the enumeration type.


int number = -1;
ArrivalStatus arrived = (ArrivalStatus) ArrivalStatus.ToObject(typeof(ArrivalStatus), number);


When converting an integer to an enumeration value, it is possible to assign a value that is not actually a member of the enumeration. To prevent this, you can pass the integer to the IsDefined method before performing the conversion. The following example uses this method to determine whether the elements in an array of integer values can be converted to ArrivalStatus values.


using System;

public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 };

public class Example
{
   public static void Main()
   {
      int[] values = { -3, -1, 0, 1, 5, Int32.MaxValue };
      foreach (var value in values)
      {
         ArrivalStatus status;
         if (Enum.IsDefined(typeof(ArrivalStatus), value))
            status = (ArrivalStatus) value;
         else
            status = ArrivalStatus.Unknown;
         Console.WriteLine("Converted {0:N0} to {1}", value, status);
      }
   }
}
// The example displays the following output:
//       Converted -3 to Unknown
//       Converted -1 to Late
//       Converted 0 to OnTime
//       Converted 1 to Early
//       Converted 5 to Unknown
//       Converted 2,147,483,647 to Unknown


Although the Enum class provides explicit interface implementations of the IConvertible interface for converting from an enumeration value to an integral type, you should use the methods of the Convert class, such as ToInt32, to perform these conversions. The following example illustrates how you can use the GetUnderlyingType method along with the Convert.ChangeType method to convert an enumeration value to its underlying type. Note that this example does not require the underlying type of the enumeration to be known at compile time.


ArrivalStatus status = ArrivalStatus.Early;
var number = Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus)));
Console.WriteLine("Converted {0} to {1}", status, number);
// The example displays the following output:
//       Converted Early to 1


Parsing Enumeration Values

The Parse and TryParse methods allow you to convert the string representation of an enumeration value to that value. The string representation can be either the name or the underlying value of an enumeration constant. Note that the parsing methods will successfully convert string representations of numbers that are not members of a particular enumeration if the strings can be converted to a value of the enumeration's underlying type. To prevent this, the IsDefined method can be called to ensure that the result of the parsing method is a valid enumeration value. The example illustrates this approach and demonstrates calls to both the Parse and Enum.TryParse(Of TEnum)(String, TEnum) methods. Note that the non-generic parsing method returns an object that you may have to cast (in C#) or convert (in Visual Basic) to the appropriate enumeration type.


string number = "-1";
string name = "Early";

try {
   ArrivalStatus status1 = (ArrivalStatus) Enum.Parse(typeof(ArrivalStatus), number);
   if (!(Enum.IsDefined(typeof(ArrivalStatus), status1)))
      status1 = ArrivalStatus.Unknown;
   Console.WriteLine("Converted '{0}' to {1}", number, status1);
}
catch (FormatException) {
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", 
                     number);
}   

ArrivalStatus status2;
if (Enum.TryParse<ArrivalStatus>(name, out status2)) {
   if (!(Enum.IsDefined(typeof(ArrivalStatus), status2)))
      status2 = ArrivalStatus.Unknown;
   Console.WriteLine("Converted '{0}' to {1}", name, status2);
}
else {
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", 
                     number);
}
// The example displays the following output:
//       Converted '-1' to Late
//       Converted 'Early' to Early


Formatting Enumeration Values

You can convert enumeration values to their string representations by calling the static Format method, as well as the overloads of the instance ToString method. You can use a format string to control the precise way in which an enumeration value is represented as a string. For more information, see Enumeration Format Strings. The following example uses each of the supported enumeration format strings to convert a member of the ArrivalStatus enumeration to its string representations.


string[] formats= { "G", "F", "D", "X"};
ArrivalStatus status = ArrivalStatus.Late;
foreach (var fmt in formats)
   Console.WriteLine(status.ToString(fmt));

// The example displays the following output:
//       Late
//       Late
//       -1
//       FFFFFFFF


Iterating Enumeration Members

The Enum type does not implement the IEnumerable or IEnumerable(Of T) interface, which would enable you to iterate members of a collection by using a foreach (in C#) or For Each (in Visual Basic) construct. However, you can enumerate members in either of two ways.

  • You can call the GetNames method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the Parse method to convert the string to its equivalent enumeration value. The following example illustrates this approach.

    
    string[] names = Enum.GetNames(typeof(ArrivalStatus));
    Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
    Array.Sort(names);
    foreach (var name in names) {
       ArrivalStatus status = (ArrivalStatus) Enum.Parse(typeof(ArrivalStatus), name);
       Console.WriteLine("   {0} ({0:D})", status);
    }
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          Early (1)
    //          Late (-1)
    //          OnTime (0)
    //          Unknown (-3)      
    
    
    
  • You can call the GetValues method to retrieve an array that contains the underlying values in the enumeration. Next, for each element of the array, you can call the ToObject method to convert the integer to its equivalent enumeration value. The following example illustrates this approach.

    
    var values = Enum.GetValues(typeof(ArrivalStatus));
    Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
    foreach (var value in values) {
       ArrivalStatus status = (ArrivalStatus) Enum.ToObject(typeof(ArrivalStatus), value);
       Console.WriteLine("   {0} ({0:D})", status);
    }                                       
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          OnTime (0)
    //          Early (1)
    //          Unknown (-3)
    //          Late (-1)
    
    
    

Non-Exclusive Members and the Flags Attribute

One common use of an enumeration is to represent a set of mutually exclusive values. For example, an ArrivalStatus instance can have a value of Early, OnTime, or Late. It makes no sense for the value of an ArrivalStatus instance to reflect more than one enumeration constant.

In other cases, however, the value of an enumeration object can include multiple enumeration members, and each member represents a bit field in the enumeration value. The FlagsAttribute attribute can be used to indicate that the enumeration consists of bit fields. For example, an enumeration named Pets might be used to indicate the kinds of pets in a household. It can be defined as follows.


[Flags] public enum Pets { None=0, Dog=1, Cat=2, Bird=4, Rodent=8,
                           Reptile=16, Other=32 };



The Pets enumeration can then be used as shown in the following example.


Pets familyPets = Pets.Dog | Pets.Cat;
Console.WriteLine("Pets: {0:G} ({0:D})", familyPets);
// The example displays the following output:
//       Pets: Dog, Cat (3)      


The following best practices should be used when defining a bitwise enumeration and applying the FlagsAttribute attribute.

  • Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

  • Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.

  • Consider creating an enumerated constant for commonly used flag combinations. For example, if you have an enumeration used for file I/O operations that contains the enumerated constants Read = 1 and Write = 2, consider creating the enumerated constant ReadWrite = Read OR Write, which combines the Read and Write flags. In addition, the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks.

  • Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors.

  • A convenient way to test whether a flag is set in a numeric value is to call the instance HasFlag method, as shown in the following example.

    
    Pets familyPets = Pets.Dog | Pets.Cat;
    if (familyPets.HasFlag(Pets.Dog))
       Console.WriteLine("The family has a dog.");
    // The example displays the following output:
    //       The family has a dog.      
    
    
    

    It is equivalent to performing a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, and then testing whether the result of that operation is equal to the flag enumerated constant. This is illustrated in the following example.

    
    Pets familyPets = Pets.Dog | Pets.Cat;
    if ((familyPets & Pets.Dog) == Pets.Dog)
       Console.WriteLine("The family has a dog.");
    // The example displays the following output:
    //       The family has a dog.      
    
    
    
  • Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. This is illustrated in the following example.

    
    Pets familyPets = Pets.Dog | Pets.Cat;
    if (familyPets == Pets.None)
       Console.WriteLine("The family has no pets.");
    else
       Console.WriteLine("The family has pets.");   
    // The example displays the following output:
    //       The family has pets.      
    
    
    
  • Do not define an enumeration value solely to mirror the state of the enumeration itself. For example, do not define an enumerated constant that merely marks the end of the enumeration. If you need to determine the last value of the enumeration, check for that value explicitly. In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid.

The following example demonstrates using an enumeration to represent named values and another enumeration to represent named bit fields.


using System;

public class EnumTest {
    enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum BoilingPoints { Celsius = 100, Fahrenheit = 212 };
    [FlagsAttribute]
    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

    public static void Main() {

        Type weekdays = typeof(Days);
        Type boiling = typeof(BoilingPoints);

        Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:");

        foreach ( string s in Enum.GetNames(weekdays) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( weekdays, Enum.Parse(weekdays, s), "d"));

        Console.WriteLine();
        Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.");
        Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:");

        foreach ( string s in Enum.GetNames(boiling) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format(boiling, Enum.Parse(boiling, s), "d"));

        Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
        Console.WriteLine();
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors);
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.

Date

History

Reason

June 2010

Revised extensively.

Customer feedback.

Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ
Enumerations are ValueTypes!!
Enumerations are derived from System.Enum which in turn is derived from System.ValueType&nbsp; in spite the fact that ValueTypes derived types are sealed which in turn makes System.Enum sealed. But this is possible because the enumerators does not explicitly inherit from Enum; the inheritance relationship is handled implicitly by the compiler. But structures are directly derived from System.ValueType so they are automatically sealed.
Constraint cannot be special class 'System.Enum'
Please vote for this issue:

"Constraint cannot be special class 'System.Enum'. Why not?"
https://connect.microsoft.com/VisualStudio/feedback/details/93336/constraint-cannot-be-special-class-system-enum-why-not