C #: from the basics to the medium level [Enum (Part I)]
Let’s talk about Enum.
If we read in the documentation
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum
An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum
keyword and specify the names of enum members.
Make an example:
think about a world direction, North, South, East and West.
We can have a const like this
every number represent a different direction.
In this situation like this, we should use an Enum.
This is the syntax for declare it
You can declare it with or without numbers, by default the Enum are mapped by an int value
As we can see, every “direction” have its own mapping number, and like Collections, the first value is zero.
This is by default, but if we need for something specific, we can assign any number to any direction.
I assign it casual numbers, and it is perfectly fine, no errors.
Now, watch out at one thing. If we not explicit assign a value inside Enum, if come back and insert another voice between North and south, look what’s happen
At beginning, North = 0 and South = 1, but when we insert NorthEast, it becomes 1, and South = 2.
That’s perfectly fine, just be careful because if we have a database that reads the Enum and we move the values, can be a problem.
At this point, how can we use Enum?
First, we need a reference and initialize the Enum
Inside Main we write
and we can choose one, I set it to North
Now, if we use Console.WriteLine(), we can read the name, or, the value.
Remember?
By default Enum has a numeric value, so we can CAST it as int if we need.
If we press “Play”
Now, if we need we can process it at reverse.
If we receiv a number, we can CAST it as Enum!
For example
Here we cast the number as Enum, and if we run the application
This is the basics to convert int to Enum and Enum to int.