Author : HASSAN MD TAREQ | Updated : 2020/08/01

What is enum in programming?

Enum in CSharp

public enum DayOfWeek : byte
{
    Mon = 1,
    Tue = 2,
    Wed = 3,
    Thu = 4,
    Fri = 5,
    Sat = 6,
    Sun = 7
}
  • Enum.Parse(typeof(DayOfWeek), "Mon");
  • Enum.IsDefined(typeof(DayOfWeek), 2);
  • Enum.GetNames(typeof(DayOfWeek))
  • Enum.GetValues(typeof(DayOfWeek)))

Convertion to int

Enum to int

var intValOfMonday = (byte)DayOfWeek.Mon;
Console.WriteLine(intValOfMonday);

Int to Enum

var dayFromInt = Enum.ToObject(typeof(DayOfWeek), 2);
Console.WriteLine(dayFromInt);

Convertion to string

Enum to string

var strSunday = DayOfWeek.Sun.ToString();
Console.WriteLine(strSunday);

Sting to Enum

try
{
    var monDay = Enum.Parse(typeof(DayOfWeek), "Mon");
    Console.WriteLine(monDay);
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.Message);
}

String list from enum

public List<string> days = Enum.GetNames(typeof(DayOfWeek)).ToList();

Iterating enum members

foreach (var day in Enum.GetValues(typeof(DayOfWeek)))
{
    Console.WriteLine(day);
}


foreach (var name in Enum.GetNames(typeof(DayOfWeek)))
{
    Console.WriteLine(name);
}

Enum to dictionary

var enumValues = Enum.GetValues(typeof(ProductionStatus)).Cast<object>()
                                .ToDictionary(enumValue => enumValue.ToString(), enumValue => (int)enumValue);

foreach (var enumValue in enumValues)
{
    Console.WriteLine("item: {0}, value: {1}", enumValue.Key, enumValue.Value.ToString("000");
}

Following code from: https://stackoverflow.com/a/17121612/4802664

public static class EnumExtensions {

    /// <summary>
    /// Gets all items for an enum value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static IEnumerable<T> GetAllItems<T>(this T value) where T : Enum {
        return (T[])Enum.GetValues(typeof(T));
    }
}

Additional links:

  • https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum