What is Enum And Why Use Enum

Introduction

 
An enum is simply a named integer constant. Many times in coding we end up in a situation where we need to declare a variable for flag purposes; eg. add, update,delete etc. It can be done either by creating an integer variable or a string variable. 
 
Example 
  1. private static void performOpration(int _operation) {  
  2.  switch (_operation) {  
  3.   case 1:  
  4.    add();  
  5.    break;  
  6.   case 2:  
  7.    update();  
  8.    break;  
  9.   case 3:  
  10.    delete();  
  11.    break;  
  12.   default:  
  13.    break;  
  14.  }  
  15. }  
Integer type flag uses less memory but code becomes difficult to uderstand since you will need to remember all the values for flags. To make your code more readable and easy to uderstand you can go with string type flag.
 
Example 
  1. private static void performOpration(string _operation) {  
  2.  switch (_operation) {  
  3.   case "add":  
  4.    add();  
  5.    break;  
  6.   case "update":  
  7.    update();  
  8.    break;  
  9.   case "delete":  
  10.    delete();  
  11.    break;  
  12.   default:  
  13.    break;  
  14.  }  
  15. }  
using string type flag your code will be more readable but there is a chance of spelling mistakes,  hence a run time error. So the best solution is enum where integers will be identified by names (fix names).
 
Example 
  1. enum Operation {  
  2.  add,  
  3.  update,  
  4.  delete  
  5. }  
  6. static void Main(string[] args) {  
  7.  Operation_operation = Operation.add;  
  8.  performOpration(_operation);  
  9. }  
  10.   
  11. private static void performOpration(Operation_operation) {  
  12.  switch (_operation) {  
  13.   case Operation.add:  
  14.    break;  
  15.   case Operation.update:  
  16.    break;  
  17.   case Operation.delete:  
  18.    break;  
  19.  }  
  20. }  
In the above code we can easily identify what is _operation is.
 
Plus there is no chance of spelling mistakes as it ends up in compile-time error. Plus internally, it's just an integer.
 
By default the first value in enum is set to 0, so in our case add is 0. We can also set the value to the enum.
 
Example 
  1. enum Operation {  
  2.  add = 10,  
  3.   update,  
  4.   delete  
  5. }  
  6. here in this  
  7. case add will set to 10 and further will automatically set by adding 1 to its previous, ,  
  8. so  
  9. add = 10, update = 11, delete = 12  
  10.   
  11. If we do something like this...  
  12.  enum Operation {  
  13.   add = 10  
  14.   update,  
  15.   delete = 30  
  16.  }  
  17. add = 10, update = 11, delete = 30  

Summary 

 
In this article, we learned about enum in C# and how to use enum in the code examples. 


Similar Articles