Enumerations or enums for short is a good programming practice to adapt, for me personally it improves the Readability and Maintainability of once programs. My experience in enums came from a project where in we are communicating to server to process the client data. We used enums to check if the request sent to the server was successful or not. To visualize the use of enums I created a sample application to simulate a scenario where connection test with server happens.
So what are enums ? Enums in c# are strongly typed named constants and we use the enum keyword to declare it. Take a look on the sample enum that I have created below:
We created an enum of ResultCode which contains different named constants from Success to UnknownError. So instead of writing the different result codes one by one and declaring it constant we created a more organize and readable way. Don’t forget in order to create an enum we need to use the enum keyword followed by the Enum Name then the lists of named constants and the closing brace should have semicolon in it and btw if you don’t assign a specific value to your created enum it will always start with 0 and increment by 1.
In the sample application we created a client server architecture where in the MainProgram is our client application and the MockServer class is our server application.
In the purpose of our demo the ConnectToServer Test requires the user to input result that It wants then displays the corresponding ResultCode Name as shown below:
We got the Success string because we have supplied the ConnectToServer a parameter of 0 which is equivalent to Success based on our enum ResultCode. So if you want to try with other results for the enum you can set the parameter from 0-4 and if you supply a value 5 to any range it will always return UnknownError. In the sample application we are just getting the Name of the ResultCode but if you want to get the value of the returned result code you need it to cast to integer because our enum is of type integer.
There are also some helpful methods to process enums one is Enum.GetName() which we have already used from the sample application another is Enum.GetNames() which gets all the list of names of created enum and lastly the Enum.GetValues() which instead of returning the names it returns the assigned values. Let’s try the Enum.GetNames() first as shown below:
So as expected we just showed the names of the constants created under the enum ResultCode. Next let’s try the Enum.GetValues() as shown below:
So as expected again the Enum.GetValues() just shows the actual default values based on the created enum ResultCode.
Enums in c# are very straight forward to used and also like I said it improves the Readability of your program because of the descriptive naming and likewise the Maintainability of your program because when you want to add a new constant you just need to update the created enum.
Happy Coding 🙂