User Tools

Site Tools


notes:csharp:enums

Enums in C#

enum BasicColor
{
    White,
    Red,
    Green,
    Blue
};
...
BasicColor color = BasicColor.Green;

Discovering Enum Values

// Get a member of an enum as a string.
string s1 = color.ToString(); // "Green"
string s2 = Enum.GetName(typeof(BasicColor), 2); // "Green" (White==0, Red==1, Green==2)
string s3 = Enum.Format(typeof(BasicColor), color, "G"); // "Green"
 
// Get a member of an enum as a formatted string.
string s4 = Enum.Format(typeof(BasicColor), color, "x"); // hexadecimal: "00000002"
string s5 = Enum.Format(typeof(BasicColor), color, "d"); // decimal: "2"
 
// Get a member of an enum from a string.
BasicColor color1 = (BasicColor)Enum.Parse(typeof(BasicColor), "Green", true);
 
// Get a member of an enum from a string in .NET 4+
BasicColor color2;
if (Enum.TryParse<BasicColor>("Green", out color2))
{
    // OK
}
 
// Determine if "Green" is a member of an enum.
// Note: Enum.IsDefined does not work for flagged enums.
if (Enum.IsDefined(typeof(BasicColor), "Green"))
{
    // ...
}
 
// Obtain the underlying type. By default enums are of type System.Int32 
// but they can derive from another numerical type.
Type type = Enum.GetUnderlyingType(typeof(BasicColor)); // Int32
 
// Special treatment of 0 in enums: 0 does not require an explicit cast.
// Reasons for the special treatment of 0:
// - The first member of an enum is often used as the default value.
// - For combined enum types, 0 means "no flags."
BasicColor defaultColor = 0; // White

Iterating Enum Values

// Get members of BasicColor as an array.
Array arr = Enum.GetValues(typeof(BasicColor));
foreach (BasicColor color in arr)
{
    // do something with color
}
 
// Get an IEnumerable collection. 
// Note: The Enum.GetEnumValues method does not guarantee that the order of enum values will be preseved.
var colors = (IEnumerable<BasicColor>)typeof(BasicColor).GetEnumValues();
foreach (BasicColor color in colors)
{
    // do something with color
}
 
// Get all members of BasicColor as strings.
foreach (string s in Enum.GetNames(typeof(BasicColor)))
{
    // do something with s
}
 
// Get all members of BasicColor as integers.
foreach (int i in Enum.GetValues(typeof(BasicColor)))
{
    // do something with i
}

Example: Obtain a collection of items containing descriptions of enum values:

// An item containing a description of an enum value.
public class Item
{
    public int Id { get; set; }
    public string Text { get; set; }
}
 
// A method to obtain a collection of items.
public static List<Item> GetEnumValues<T>() where T : struct
{
    List<Item> list = new List<Item>();
    var values = (IEnumerable<T>)typeof(T).GetEnumValues();
    foreach (T v in values)
    {
        list.Add(new Item { Id = Convert.ToInt32(v), Text = v.ToString() });
    }
    return list;
}
 
...
 
// An example usage.
public enum BasicColor
{
    White,
    Red,
    Green,
    Blue
};
 
List<Item> colors = GetEnumValues<BasicColor>();
...

Enum Values as Bit Flags

[Flags]
enum ReportStyles
{
    None = 0x00,
    Header = 0x01,
    Footer = 0x02,
    PageNo = 0x04,
    Grouping = 0x08,
    Summary = 0x10,
    All = 0x1F
}
// A report with a header and a footer.
ReportStyles style1 = ReportStyles.Header | ReportStyles.Footer; // 0x03
 
// A report with all styles except summary.
ReportStyles style2 = ReportStyles.All ^ ReportStyles.Summary; // 0x0F
 
// A report with a page number and a summary.
// Make sure that a header and a footer are not included.
ReportStyles style3 =
    (((ReportStyles.PageNo | ReportStyles.Summary) & ~ReportStyles.Header) & ~ReportStyles.Footer); // 0x14
 
// Test if a style includes a page number.
if ((style3 & ReportStyles.PageNo) == ReportStyles.PageNo)
{
    // the style includes ReportStyles.PageNo
}
 
// Test if a style does not include a page number.
if ((style3 & ReportStyles.PageNo) == ReportStyles.None)
{
    // the style does not include ReportStyles.PageNo
}

Enum.IsDefined does not work for flagged enums. This is an equivalent method:

bool IsFlagDefined(Enum e)
{
    decimal d;
    return !decimal.TryParse(e.ToString(), out d);
}
notes/csharp/enums.txt · Last modified: 2017/02/08 by admin