How To Play With Enum in C#

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

Sample enum variables to use:

  1. internal enum MicrosoftOffice  
  2. {  
  3.     Word = 0,  
  4.     Excel = 1,  
  5.     Powerpoint = 3,  
  6.     Visio = 5  
  7. }  

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.
  1.  /// This is used to get Enum name by its value as integer.  
  2.   
  3. private static void GetEnumName()  
  4. {  
  5.     int[] enumValues = new int[] { 0, 1, 3, 5 };  
  6.     foreach (int enumValue in enumValues)  
  7.     {  
  8.         Console.WriteLine(Enum.GetName(typeof(MicrosoftOffice), enumValue));  
  9.     }  
  10.     Console.ReadKey();  
  11. }  
Output

1st.jpg

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

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

  1. /// This is used to iterate enum variables.  
  2. private static void IterateEnumVariables()  
  3. {  
  4.     Console.WriteLine("List of Enums");  
  5.     string[] officenames = Enum.GetNames(typeof(MicrosoftOffice));   
  6.     foreach (string officename in officenames)  
  7.     {  
  8.         Console.WriteLine(officename);  
  9.     }   
  10.     Console.ReadKey();  
  11. }  
Output

2nd.jpg

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

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

  1. ///This is used to get Enum values as array.  
  2.   
  3. private static void GetEnumValues()  
  4. {  
  5.     Array enumValueArray = Enum.GetValues(typeof(MicrosoftOffice));  
  6.     foreach (int enumValue in enumValueArray)  
  7.     {  
  8.         Console.WriteLine("Name: " + Enum.GetName(typeof(MicrosoftOffice), enumValue) + " , Value: " + enumValue);  
  9.     }  
  10.     Console.ReadKey();  
  11. }  
Output

3rd.jpg

How to convert an enum to a String in C#?

ToString() converts Enum to string.

  1. /// This is used to convert Enum to string.  
  2.   
  3.  private static void EnumToString()  
  4.  {  
  5.      Console.WriteLine("Converting Enum to String");  
  6.      Console.WriteLine(MicrosoftOffice.Powerpoint.ToString());  
  7.      Console.WriteLine(MicrosoftOffice.Word.ToString())  
  8.      Console.ReadKey();  
  9.  }  
Output

 4th.jpg

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.

  1. /// <summary>  
  2. /// This is used to convert string to Enum variable.  
  3. /// </summary>  
  4. private static void ParseEnum()  
  5. {  
  6.     MicrosoftOffice ms = (MicrosoftOffice)Enum.Parse(typeof(MicrosoftOffice), "Word");  
  7.     Console.WriteLine(ms.ToString());  
  8.    MicrosoftOffice ms1 = (MicrosoftOffice)Enum.Parse(typeof(MicrosoftOffice), "Excel");  
  9.     Console.WriteLine(ms1.ToString());   
  10.     Console.ReadKey();  
  11. }  
Output

 5th.jpg

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.

  1. /// <summary>  
  2. /// This is used to check and get value of specified string.  
  3. /// </summary>  
  4. private static void TryParseEnum()  
  5. {  
  6.     MicrosoftOffice msDefault = MicrosoftOffice.Powerpoint;  
  7.     //Supplying correct enum string.  
  8.     bool ms = Enum.TryParse("Word"trueout msDefault);  
  9.     Console.WriteLine(ms.ToString() + " " + msDefault.ToString());  
  10.     MicrosoftOffice msDefault1 = MicrosoftOffice.Powerpoint;  
  11.     //Supplying wrong enum string.  
  12.     bool ms1 = Enum.TryParse("excl"out msDefault1);  
  13.     Console.WriteLine(ms1.ToString() + " " + msDefault1.ToString());  
  14.     Console.ReadKey();  
  15. }  
Output

6th.jpg

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.

  1. /// This is used to check whether the enum is available in Enum type.  
  2.   
  3.  private static void EnumIsDefined()  
  4.  {  
  5.      if (Enum.IsDefined(typeof(MicrosoftOffice), "Word"))  
  6.      {  
  7.          Console.WriteLine("Word Enum Exists");  
  8.      }   
  9.      if (Enum.IsDefined(typeof(MicrosoftOffice), "Excl"))  
  10.      {  
  11.          Console.WriteLine("Excel Enum Exists");  
  12.      }  
  13.      else  
  14.      {  
  15.          Console.WriteLine("Enum Not Exists");  
  16.      }  
  17.      Console.ReadKey();  
  18.   }  
Output

7th.jpg

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 follow

  • 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#:

  1. internal enum MicrosoftOfficeString : int  
  2. {  
  3.     [EnumStringAttribute("Microsoft Word")]  
  4.     Word = 0,  
  5.     [EnumStringAttribute("Microsoft Excel")]  
  6.     Excel = 1,  
  7.     [EnumStringAttribute("Microsoft Powerpoint")]  
  8.     Powerpoint = 3,  
  9.     [EnumStringAttribute("Microsoft Visio")]  
  10.     Visio = 5  
  11. }  
2. How to create a custom attribute for a custom string value in C#?
  1. public class EnumStringAttribute : Attribute  
  2. {  
  3.     public EnumStringAttribute(string stringValue)  
  4.     {  
  5.         this.stringValue = stringValue;  
  6.     }  
  7.     private string stringValue;  
  8.     public string StringValue  
  9.     {  
  10.         get { return stringValue; }  
  11.         set { stringValue = value; }  
  12.     }  
  13. }  
3. How to create an extension method for an enum custom String?
  1. public static class ExtenstionClass  
  2. {  
  3.     public static string GetStringValue(this Enum value)  
  4.     {  
  5.         Type type = value.GetType();  
  6.         FieldInfo fieldInfo = type.GetField(value.ToString());  
  7.         // Get the stringvalue attributes  
  8.        EnumStringAttribute[] attribs = fieldInfo.GetCustomAttributes(  
  9.             typeof(EnumStringAttribute), falseas EnumStringAttribute[];  
  10.          // Return the first if there was a match.  
  11.         return attribs.Length > 0 ? attribs[0].StringValue : null;  
  12.     }  
  13. }  
4. How to get a custom String value from an enum variable using attribute in C#?
  1.        /// This  is used to get the Cutom Attribute.  
  2.        /// </summary>  
  3.        private static void GetEnumCustomAttributeString()  
  4.        {  
  5.            //This return the custom attribute string value.  
  6.            Console.WriteLine(MicrosoftOfficeString.Excel.GetStringValue());  
  7.            Console.WriteLine(Environment.NewLine);   
  8.            string[] officenames = Enum.GetNames(typeof(MicrosoftOffice));   
  9.            foreach (string officename in officenames)  
  10.            {  
  11. MicrosoftOfficeString ms = (MicrosoftOfficeString)Enum.Parse(typeof(MicrosoftOfficeString), officename);  
  12.                //This return the custom attribute string value.  
  13.                Console.WriteLine(ms.GetStringValue());  
  14.            }  
  15.            Console.ReadKey();  
  16.        }  
Output

 8th.jpg


Similar Articles