C-SHARP - 3.14 Enum
Hello everyone and welcome to this new video. In this video, we will discuss the notion of enumerations in C#. What is an enumeration? This is something that will allow us to group several constants to make our code easier to read. Now imagine that we want to define values that will correspond to a day of the week, we will do const int Monday = 1 const int Tuesday = 2 etc this can very quickly become very long and overload our coded. Thanks to the enumeration? This will allow us to avoid this. To create an enum it is very simple, you go outside the main method, but in the class program you type enum then you give it a name we are the days of the week so I will write DaysWeeks and then we open the braces inside, we will put the days of the week, Monday, Tuesday, Wednesday etc. Until Sunday. And we have now created our enumeration. Know that each constant defined in the enumerations starts by default at zero and the default type of an enumeration is int, but it is possible to specify the type by typing here: int short etc. You choose the one you want, it is according to your need. But here it is not mandatory because by default it is an int. So you see how enumerations make our life easier, no need to write const int and initialize our constants each time. Everything is done automatically Another thing, if you want us to start with 1 instead of zero, you can on the first constant type = 1 and the rest of the constants will increment by 1 with each new constant. It is also possible to assign the same value to several constants, for example in the context where if our program sends us errors, we can classify certain errors at an equal level of seriousness. For example, we have several errors which are different but which have the same level of gravity so they will be assigned the same value. So we then go to the main method now, and we will now create a DayWeeks type variable then we will give it a name for example day and to call a constant of the enumeration, you fill in its type DaysWeeks point the constant that you want to recover. For example Monday, then you type Console.WriteLine() and between the parentheses, you put the variable day If we launch the program, we have Monday which is displayed And if we want to recover the value of Monday, a new notion before the day variable in the Console.WriteLine() you make parentheses and inside you put an int And if we replace Monday by Saturday for example, we will have the value 6 Here it is a way of recovering the value of a constant of an enumeration Here I think that I have covered all the main points to know about enumerations, we will deepen with more advanced notions in future lessons. In the next video, I will give you a very simple little exercise to practice on this notion of enumeration. Come on, let's go, see you right away!