Author : MD TAREQ HASSAN | 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
}

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");
}

Enum Extension for Description

EnumExtensions.cs

using System;
using System.ComponentModel;

namespace Foo.Enums.Extensions
{
    public static class EnumExtensions
    {
        //
        //  MetaData attribute
        //
        public static T GetAttribute<T>(this Enum value) where T : Attribute
        {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);

            // check if no attributes have been specified.
            if (attributes.Length > 0)
            {
                return (T)attributes[0];
            }
            else
            {
                return null;
            }
        }

        //
        // Description MetaData attribute.
        //
        public static string GetDescription(this Enum value)
        {
            var attribute = value.GetAttribute<DescriptionAttribute>();
            var descriptionAttribute = attribute == null ? String.Empty : attribute.Description;
            return descriptionAttribute;
        }

        /// <summary>
        /// Find the enum from the description attribute.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="description"></param>
        /// <returns></returns>
        public static T FromDescription<T>(this string description) where T : struct
        {
            string attr;
            bool found = false;
            T result = (T)Enum.GetValues(typeof(T)).GetValue(0);

            foreach (object enumVal in Enum.GetValues(typeof(T)))
            {
                attr = ((Enum)enumVal).GetDescription();

                if (attr == description)
                {
                    result = (T)enumVal;
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                throw new Exception();
            }

            return result;
        }
    }
}

Enum Extension to Convert to Disctionary

EnumExtensions.cs

public static IDictionary<string, int> ToDictionary(this Type enumType)
{
    return Enum.GetValues(enumType)
    .Cast<object>()
    .ToDictionary(v => ((Enum)v).GetDescription(), k => (int)k); 
}

// Now call this like...
var dic = typeof(ActivityType).ToDictionary();
EnumDecription Ext Method

Other extension methods

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: