This topic has not yet been rated - 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)
[ComVisibleAttribute(true)]
public abstract class Enum : ValueType, 
	IComparable, IFormattable, IConvertible

The Enum type exposes the following members.

  Name Description
Protected method Supported by Silverlight for Windows Phone Supported by Xbox 360 Enum Initializes a new instance of the Enum class.
Top
  Name Description
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 CompareTo Compares this instance to a specified object and returns an indication of their relative values.
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 Equals Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).)
Protected method Supported by Silverlight for Windows Phone Supported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 GetHashCode Returns the hash code for the value of this instance. (Overrides ValueType.GetHashCode().)
Public method Static member Supported by Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 GetTypeCode Returns the underlying TypeCode for this instance.
Public method Static member Supported by Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 IsDefined Returns an indication whether a constant with a specified value exists in a specified enumeration.
Protected method Supported by Silverlight for Windows Phone Supported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Static member Supported by Silverlight for Windows Phone Supported by Xbox 360 Parse 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 Supported by Silverlight for Windows Phone Supported by Xbox 360 ToObject Returns an instance of the specified enumeration set to the specified value.
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 ToString() Converts the value of this instance to its equivalent string representation. (Overrides ValueType.ToString().)
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 ToString(IFormatProvider) Obsolete. This method overload is obsolete; use Enum.ToString().
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 ToString(String) Converts the value of this instance to its equivalent string representation using the specified format.
Public method Supported by Silverlight for Windows Phone Supported by Xbox 360 ToString(String, IFormatProvider) Obsolete. This method overload is obsolete; use Enum.ToString(String).
Public method Static member TryParse<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<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 Silverlight for Windows Phone Supported by Xbox 360 IConvertible.ToBoolean Infrastructure. Converts the current value to a Boolean value based on the underlying type.
Explicit interface implemetation Private method Supported by Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 IConvertible.ToChar Infrastructure. Converts the current value to a Unicode character based on the underlying type.
Explicit interface implemetation Private method Supported by Silverlight for Windows Phone Supported by Xbox 360 IConvertible.ToDateTime Infrastructure. Converts the current value to a DateTime based on the underlying type.
Explicit interface implemetation Private method Supported by Silverlight for Windows Phone Supported by Xbox 360 IConvertible.ToDecimal Infrastructure. Converts the current value to a Decimal based on the underlying type.
Explicit interface implemetation Private method Supported by Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 IConvertible.ToType Infrastructure. Converts the current value to a specified type based on the underlying type.
Explicit interface implemetation Private method Supported by Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 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 Silverlight for Windows Phone Supported by Xbox 360 IConvertible.ToUInt64 Infrastructure. Converts the current value to a 64-bit unsigned integer based on the underlying type.
Top

An enumeration is a named constant whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values.

Caution note Caution:

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

Enum provides methods to compare instances of this class, convert the value of an instance to its string representation, convert the string representation of a number to an instance of this class, and create an instance of a specified enumeration and value.

You can also treat an enumeration as a bit field. For more information, see FlagsAttribute.

Implemented Interfaces

This class inherits from ValueType, and implements the IComparable, IFormattable, and IConvertible interfaces. Use the Convert class for conversions instead of this class' explicit interface member implementation of IConvertible.

Guidelines for FlagsAttribute and Enum

  • 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 perform 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, then test whether the result of that operation is equal to the flag enumerated constant.

  • 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.

    If you create a value enumeration instead of a flags enumeration, it is still worthwhile to create a None enumerated constant. The reason is that 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 your application needs to represent, consider using an enumerated constant whose value is zero to represent the default. If there is no default case, consider using an enumerated constant whose value is zero that means the case that is not represented by any of the other enumerated constants.

  • 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.

  • 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.

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


using System;

public class Example
{
   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 Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      Type weekdays = typeof(Days);

      outputBlock.Text += String.Format("The day of the week today is {0}.", 
                          Enum.Parse(weekdays, DateTime.Now.DayOfWeek.ToString(), false));
      outputBlock.Text += "\n";

      outputBlock.Text += "Enums can also represent some meaningful value. For example:" + "\n";
      outputBlock.Text += String.Format("The BoilingPoints Enum defines the following items, and corresponding values:") + "\n";
      outputBlock.Text += String.Format("   The boiling point in degrees {0:G} is {0:D}.", 
                                        BoilingPoints.Celsius) + "\n";
      outputBlock.Text += String.Format("   The boiling point in degrees {0:G} is {0:D}.", 
                                        BoilingPoints.Fahrenheit) + "\n";

      Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
      outputBlock.Text += String.Format("myColors holds the following combination of colors: {0}", myColors) + "\n";
   }
}


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

This type is thread safe.

Date

History

Reason

June 2010

Added warning about non-integer enumerations.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
GetNames, GetValues

How can these methods be substituted to achieve iteration throgh the values?

Substitutes for Enum.GetNames, Enum.GetValues


In the absence of the Enum.GetNames and Enum.GetValues methods, which are not supported in Silverlight, you can use reflection to iterate the public static fields of an enumeration type. Each field is represented by a FieldInfo object. Its Name property returns the name of the enumeration member. Its GetValue property returns the underlying value of the enumeration member.

This gives you a choice of how you want to create enumeration instances when you iterate the enumeration type's public static fields. You can retrieve their names and pass them to the Enum.Parse method. You can retrieve their values and pass them to the Enum.ToObject method. Or you can retrieve their values and cast them (in C#) or convert them (in Visual Basic) to enumeration values.

The following is some C# code that enumerates the fields of the DayOfWeek enumeration and instantiates DayOfWeek values in these three ways:

using System;
using System.Reflection;
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
DayOfWeek day = DayOfWeek.Sunday;
Type dayOfWeekType = day.GetType();
BindingFlags flags = BindingFlags.Static | BindingFlags.Public;
// Iterate the enumeration's public fields and instantiate enum values from names.
outputBlock.Text += "\nInstantiating Enum objects from their names:\n";
foreach (FieldInfo fld in dayOfWeekType.GetFields(flags))
{
// Get the name of the enumeration member.
string name = fld.Name;
// Use the name to instantiate an enum value.
DayOfWeek dow = (DayOfWeek) Enum.Parse(dayOfWeekType, name, true);
outputBlock.Text += String.Format("{0:F}: {0:d}\n", dow);
}

outputBlock.Text += "\nInstantiating Enum objects from their values:\n";
foreach (FieldInfo fld in dayOfWeekType.GetFields(flags))
{
// Get the value of the enumeration member and use it to instantiate an enum value.
DayOfWeek dow = (DayOfWeek) Enum.ToObject(dayOfWeekType, fld.GetValue(null));
outputBlock.Text += String.Format("{0:F}: {0:d}\n", dow);
}
outputBlock.Text += "\nUsing casting to instantiate Enum objects from their values:\n";
foreach (FieldInfo fld in dayOfWeekType.GetFields(flags))
{
// Get the value of the enumeration member and cast it to an enum value.
DayOfWeek dow = (DayOfWeek) fld.GetValue(null);
outputBlock.Text += String.Format("{0:F}: {0:d}\n", dow);
}
}
}



--Ron Petrusha
Common Language Runtime Developer Content
Microsoft Corporation