We are back with another C# lesson. As you may know already, C# is a pretty simple programming language with an easy syntax that is extremely easy to pick up and put to practical use. That being said, once you begin learning C#, it is important to follow it up with regular and consistent practice. This is because only practice will help you learn C# faster than ever and help you become a total pro when it comes to C#. Speaking of mastering C#, one concept that everybody must know about is the C# enum or an enumeration. Before we get into the intricacies of what this term implies, let us understand what it is and what is the C# enumeration definition.
Table of Contents
What is a C# enum?
A C# enum is a strongly typed constant. Simply put, in C#, an ‘enum’ signifies a special class that consists of unchangeable variables. Even though enums are variables, they are classified as ‘constants.’ Programmers generally use these enums with switch statements to check the effects of one variable on the following statements and results. The value of an enum has to be explicitly assigned and modified by the programmer, thus remaining constant otherwise. This constant variable then affects the following variables. The default value for the first enum character is 0 and then 1 and so on.
This C# enum can be used using the ‘enum’ keyword, directly inside the namespacem a class or even a structure. This is how you can define an enum in your code:
C# Enum example:
namespace csharp
{
public class Program
{
public state void Main(string[] args)
{
}
enum Months
// You can add any item or concept instead of ‘months’ This is just for the sake of this example. Also note that the first item in your list will have a value of ‘0,’ and then the next item will have a value of 1, then 2 and so on. To change this, you can modify the value of one of the variables and the ones before and after that particular variable will follow suit automatically. To check the value of a variable in your C# enum, simply hover over it with your mouse.
{
January = 1,
February,
March,
April,
May,
June
}
}
}
If you wish to retrieve the value of a particular variable in your enum, you can do so by specifying the type of data that the value is in. In this case, you can see that the value we attributed to January is 1 which is an ‘int’ (integer) Thus, to recall the value you assigned in the C# enum to int data type of value, you can do the following.
namespace csharp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine((int)Months.June);
}
enum Months
{
January = 1,
February,
March,
April,
May,
June
}
}
}
OUTPUT:
6
A C# enum is mostly used to make code more readable, As we can see in the example above, we did not have to specify that the first month of the year is January, the second is February, and so on. All we had to do was specify one of the variables, and the enums adapt on their own. Enums make the code more accessible by giving related constants a meaningful name. It is also widely used to test codes.
One must remember that enums cannot be used with the ‘string’ data type. So, before you add your value inside quotation marks and add other elements to connect your C# enum to string, just know that it cannot be done and you will only be thrown an exception.
Enum is an abstract class that includes static helper methods to work with enums. Some of the main methods are as follows:
- GetName () – Returns the name of the constant of the specified value of specified enum.
- GetNames () – Returns an array of string name of all the constant of specified enum.
- TryParse () – Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The reurn value indicates whether the conversion succeeded or not.
Without further ado, let us try these three main methods in enum to see what results they provide.
namespace csharp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(“GetName()”);
Console.WriteLine(Enum.GetName(typeof(Months),5))
Console.WriteLine(“GetNames()”);
foreach(string str in Enum.GetNames(typeof(Months)))
Console.WriteLine(str);
Console.WriteLine(“TryParse()”);
// The TryParse method will return a value which indicates whether the conversion succeeded or not, thus, we will have to define a variable of the enum that you have established
Months mtEnum;
Enum.TryParse<Months>(“1” out mtEnum);
Console.WriteLine(mtEnum);
// What this simply does is, it checks for the value ‘1’ in the enum that we have defined as ‘mtEnum’ If the value exists, it will convert it to the actual Month name ‘January’ and display that.
}
enum Months
{
January = 1,
February,
March,
April,
May,
June
}
}
}
OUTPUT:
GetName()
May
GetNames()
January
February
March
April
May
June
TryParse()
January
As you can see, the ‘GetName()’ method helped us recall the name of the month to which we had attributed the value ‘5’. The ‘GetNames()’ method helped us recall all the elements within the ‘Months’ enum that we had established and finally, the ‘TryParse()’ method helped us identify a variable for our enum, establish a particular value and the retrieve the element that corresponds to that particular value. In the above-mentioned example, ‘mtEnum’ was the variable and ‘1’ was the value. If the value ‘1’ existed within the variable ‘mtEnum,’ then the program would generate the element that is associated with the value ‘1’, which is ‘January’.
Ideally, you should always use C# enums especially when variable, mostly a parameter of a method, can not take more than one out of a small group of values. The use of enums instead of string codes or integers you can significantly avoid errors from passing as invalid constants by increasing compile time.
Another factor to remember is that the usage of too many enums within your code signifies that your methods are doing way too much. It is always better to not have just one method that takes up all the responsibilities, but instead, have several separate methods that can divide the tasks and increase overall compile time. All in all, C# enums increase the likelihood of accuracy and accessibility in terms of how understandable your code is, without the need to write a lot of unnecessary jargon.
And with that, we come to an end with our crash course on how to go about using C# enums, why you should use them, and how you can make them work for you. Enums, if used well, can improve your C# journey and ease your learning experience. Most C# programmers use enums and other such concepts as shortcuts to otherwise long and cumbersome coding processes. You can also lookup how to associate other types of data to your enums to further learn about this particular topic, but this article should give you more than enough material to get you started and want to learn more.
Do you know? |
---|
1. C# Enum |
2. C# Dictionary |
3. C# Switch Case |
4. C# Substring |
5. C# Foreach |