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
- private static void performOpration(int _operation) {
- switch (_operation) {
- case 1:
- add();
- break;
- case 2:
- update();
- break;
- case 3:
- delete();
- break;
- default:
- break;
- }
- }
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
- private static void performOpration(string _operation) {
- switch (_operation) {
- case "add":
- add();
- break;
- case "update":
- update();
- break;
- case "delete":
- delete();
- break;
- default:
- break;
- }
- }
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
- enum Operation {
- add,
- update,
- delete
- }
- static void Main(string[] args) {
- Operation_operation = Operation.add;
- performOpration(_operation);
- }
-
- private static void performOpration(Operation_operation) {
- switch (_operation) {
- case Operation.add:
- break;
- case Operation.update:
- break;
- case Operation.delete:
- break;
- }
- }
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
- enum Operation {
- add = 10,
- update,
- delete
- }
- here in this
- case add will set to 10 and further will automatically set by adding 1 to its previous, ,
- so
- add = 10, update = 11, delete = 12
-
- If we do something like this...
- enum Operation {
- add = 10
- update,
- delete = 30
- }
- 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.