Knowledge Management Banner

Knowledge Management Banner

C# : Enums : Part 17

  • Enums are said as strongly typed constants
  • When integral numbers are used for specifying any value than enums are used.
  • If a program uses set of integral numbers consider them replacing with enums which makes the code more readable and maintainable.

  • Consider example of program without using enum i.e. by using integral numbers to specify a value

  •  namespace IntegralNumbers  
     {  
       class Program  
       {  
         //Indication  
         //1 - Male  
         //2 - Female  
         public static void PrintGender(int num)  
         {  
           switch (num)  
           {  
             case 1:  
               Console.WriteLine("Gender is : Male");  
               break;  
             case 2:  
               Console.WriteLine("Gender is : Female");  
               break;  
             default:  
               Console.WriteLine("No Gender Specified");  
               break;  
           }  
         }  
         static void Main(string[] args)  
         {  
           PrintGender(2);  
         }  
       }  
     }  
    
  • In above example you can see that 1 represents male and 2 represents female, thus this can be said as using numbers to specify value, hence in above consition enums can be used to make code more readable.

  • Consider example below using enum.

  •  namespace Enum  
     {  
       class Program  
       {  
         public enum Gender  
         {  
           Male,  
           Female  
         }  
         public static void PrintGender(Gender gen)  
         {  
           switch (gen)  
           {  
             case Gender.Male:  
               Console.WriteLine("Gender is : Male");  
               break;  
             case Gender.Female:  
               Console.WriteLine("Gender is : Female");  
               break;  
             default:  
               Console.WriteLine("No Gender Specified");  
               break;  
           }  
         }  
         static void Main(string[] args)  
         {  
           PrintGender(Gender.Male);  
         }  
       }  
     }  
    
  • In above example enums are used for specifying values, which makes the code more readable.

No comments

Powered by Blogger.