18 Jun

[Flags] Enum Attribute And Bitwise Operation In C#

The flags attribute should be used whenever the enumerable represents a collection of flags, rather than a single value. We must use multiples of two in our enumeration to use bitwise operations. Such collections are usually manipulated using bitwise operators, For example:

MyColors themeColors = MyColors.Yellow | MyColors.Red;

Example enum decleration:

    [Flags]
    public enum MyColors : int
    {
        Yellow  = 1,
        Green   = 2,
        Red     = 4,
        Blue    = 8,
        Orange  = 16,
        Black   = 32,
        White   = 64,
    }

The flags attribute doesn’t change enum values. It is enable a nice representation by the .ToString() method:

"themeColors.ToString" =>  "Yellow, Red"

Enumeration values looks like this:
Yellow = 0000001
Green = 0000010
Red = 0000100
Blue = 0001000
Orange = 0010000
Black = 0100000
White = 1000000

themeColors instance looks like this:
themeColors = 0000101

To retrieve the distinct values in our property one can do this,
Usage:

            if ((themeColors & MyColors.Red) == MyColors.Red)
            {
                Console.WriteLine("Red is a theme color.");
            }

            if ((themeColors & MyColors.Green) == MyColors.Green)
            {
                Console.WriteLine("Green is a theme color.");
            }

themeColors is 0000101
MyColor.Red is 0000100
———————————–(BITWISE AND)
Result is 0000100 -> It is a red color

Also we can use the bit-shifting for setting the enum values. It is more simple and more readable.
Example enum decleration using bit-shifting:

    /// 
    /// using bit-shifting
    /// 
    [Flags]
    public enum MyColors_SetValuesWithBitShifting
    {
        Yellow  = 1 << 0,
        Green   = 1 << 1,
        Red     = 1 << 2,
        Blue    = 1 << 3,
        Orange  = 1 << 4,
        Black   = 1 << 5,
        White   = 1 << 6,
    }
17 Jun

Get Enum Description From Value in C#

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. We can define the attributes for enum and if you want to fetch these description simply, we can use as shown below.

Usage:

            string description = EnumHelper.StringValueOf(SiteType.Technology);
            Console.WriteLine(description);
            //Output:
            //This is a technology site.

Sample Code:

    public class EnumHelper
    {
        public static string StringValueOf(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }
    }