How to Play With Enum in C#


In this article you will see use of enum variables in C#.

Step 1: Sample enum variables to use:

internal
enum MicrosoftOffice
{
    Word = 0,
    Excel = 1,
    Powerpoint = 3,
    Visio = 5
}

Step 2: How to get enum variable name by its value in C# ?

     Retrieves the name of the constant in the specified enumeration that has the specified value.

         /// This is used to get Enum name by its value as interger.
   
        private static void GetEnumName()
        {
            int[] enumValues = new int[] { 0, 1, 3, 5 };
            foreach (int enumValue in enumValues)
            {
                Console.WriteLine(Enum.GetName(typeof(MicrosoftOffice), enumValue));
            }
            Console.ReadKey();
        }

Output

1st.jpg

Step 3: How to iterate an enum variable or enum name in C#?

Retrieves an array of the names of the constants in a specified enumeration.

             /// This is used to iterate enum variables.
        private static void IterateEnumVariables()
        {
            Console.WriteLine("List of Enums");
            string[] officenames = Enum.GetNames(typeof(MicrosoftOffice)); 
            foreach (string officename in officenames)
            {
                Console.WriteLine(officename);
            } 
            Console.ReadKey();
        }

Output

2nd.jpg

Step 4: How to get enum variable name by its value in C#?

Retrieves an array of the values of the constants in a specified enumeration.

        /// This  is used to get Enum values as array.
   
        private static void GetEnumValues()
        {
            Array enumValueArray = Enum.GetValues(typeof(MicrosoftOffice));
            foreach (int enumValue in enumValueArray)
            {
                Console.WriteLine("Name: " + Enum.GetName(typeof(MicrosoftOffice), enumValue) + " , Value: " + enumValue);
            }
            Console.ReadKey();
        }

Output

3rd.jpg

Step 5: How to convert an enum to a String in C#?

                ToString() converts Enum to string.
       /// This is used to convert Enum to string.
   
        private static void EnumToString()
        {
            Console.WriteLine("Converting Enum to String");
            Console.WriteLine(MicrosoftOffice.Powerpoint.ToString());
            Console.WriteLine(MicrosoftOffice.Word.ToString())
            Console.ReadKey();
        }

Output

 4th.jpg

Step 6: How to convert a String to an enum or Parse in C#?

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

        /// <summary>
        /// This is used to convert string to Enum variable.
        /// </summary>
        private static void ParseEnum()
        {
            MicrosoftOffice ms = (MicrosoftOffice)Enum.Parse(typeof(MicrosoftOffice), "Word");
            Console.WriteLine(ms.ToString());
           
MicrosoftOffice ms1 = (MicrosoftOffice)Enum.Parse(typeof(MicrosoftOffice), "Excel");
            Console.WriteLine(ms1.ToString()); 
            Console.ReadKey();
        }

Output

 5th.jpg

Step 7: How to check and Parse a String from the enum variable using C#?

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.

It is optionally case sensitive; you can just specify true or false to specify the option.

        /// <summary>
        /// This is used to check and get value of specified string.
        /// </summary>
        private static void TryParseEnum()
        {
            MicrosoftOffice msDefault = MicrosoftOffice.Powerpoint;
            //Supplying correct enum string.
            bool ms = Enum.TryParse("Word", true, out msDefault);
            Console.WriteLine(ms.ToString() + " " + msDefault.ToString());
            MicrosoftOffice msDefault1 = MicrosoftOffice.Powerpoint;
            //Supplying wrong enum string.
            bool ms1 = Enum.TryParse("excl", out msDefault1);
            Console.WriteLine(ms1.ToString() + " " + msDefault1.ToString());
            Console.ReadKey();
        }

Output

6th.jpg

Step 8: How to check whether the passed enum exists or not using C#?

Indicates whether a constant with a specified value exists in a specified enumeration.

/// This is used to check whether the enum is available in Enum type.

        private static void EnumIsDefined()
        {
            if (Enum.IsDefined(typeof(MicrosoftOffice), "Word"))
            {
                Console.WriteLine("Word Enum Exists");
            } 
            if (Enum.IsDefined(typeof(MicrosoftOffice), "Excl"))
            {
                Console.WriteLine("Excel Enum Exists");
            }
            else
            {
                Console.WriteLine("Enum Not Exists");
            }
            Console.ReadKey();
         }


Output

7th.jpg

Step 9: How to create a Custom String value from an enum variable and how to use it?

        This is used to set the Custom string to the enum variable as an attribute and get the value at runtime.

Here we can use any custom string to the enum variable so that it is very handy to use this custom string.

Steps to follows

  •   First create a sample set of enum variables.

  •   Then, create a custom attribute class for just custom String Value.

  •   Create an extension method for just enum.

  •   Use the extension method to get just enum custom string value.

1.  Enum variable for custom String value in C#:

internal
enum MicrosoftOfficeString : int
{
    [EnumStringAttribute("Microsoft Word")]
    Word = 0,
    [EnumStringAttribute("Microsoft Excel")]
    Excel = 1,
    [EnumStringAttribute("Microsoft Powerpoint")]
    Powerpoint = 3,
    [EnumStringAttribute("Microsoft Visio")]
    Visio = 5
}

2. How to create a custom attribute for a custom string value in C#?

public
class EnumStringAttribute : Attribute
{
    public EnumStringAttribute(string stringValue)
    {
        this.stringValue = stringValue;
    }
    private string stringValue;
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

3. How to create an extension method fore an enum custom String?

public
static class ExtenstionClass
{
    public static string GetStringValue(this Enum value)
    {
        Type type = value.GetType();
        FieldInfo fieldInfo = type.GetField(value.ToString());
        // Get the stringvalue attributes
       EnumStringAttribute[] attribs = fieldInfo.GetCustomAttributes(
            typeof(EnumStringAttribute), false) as EnumStringAttribute[];
         // Return the first if there was a match.
        return attribs.Length > 0 ? attribs[0].StringValue : null;
    }
}

4. How to get a custom String value from an enum variable using attribute in C#?

        /// This  is used to get the Cutom Attribute.
        /// </summary>
        private static void GetEnumCustomAttributeString()
        {
            //This return the custom attribute string value.
            Console.WriteLine(MicrosoftOfficeString.Excel.GetStringValue());
            Console.WriteLine(Environment.NewLine); 
            string[] officenames = Enum.GetNames(typeof(MicrosoftOffice)); 
            foreach (string officename in officenames)
            {
 MicrosoftOfficeString ms = (MicrosoftOfficeString)Enum.Parse(typeof(MicrosoftOfficeString), officename);
                //This return the custom attribute string value.
                Console.WriteLine(ms.GetStringValue());
            }
            Console.ReadKey();
        }

Output

 8th.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all