After reading this blog, you will learn the below points,
- What is Enumeration
- Advantages
- Syntax with examples
What is Enumeration?
Enumerations type specifies a group of named numeric constants; it is a user defined type, which means we can create an enumeration type, declare variable to that type and then assign values to those variables.
Main purpose of using enumeration is to represent constant values.
Advantages
- Makes our code easier to maintain by ensuring our variables are assigned only anticipated values.
- We can assign identifiable names to the values.
- Allows us to specify a set of constant values and define a type that will accept values from only that set.
- When we assign enumeration values, Microsoft intellisense displays a list of possible values that we can use.
Syntax with Example
We can create enumeration type by using enum keyword, assigning a name and then listing the values that our enumeration can take.
Eg
- enum Planet {
- Mercury,
- Venus,
- Earth,
- Mars
- }
Above code will create a new type, Planet. We can declare variables of this type and assign them values from the enumeration list
When we are referring to a specific member in enumerations, we use enumeration name and dot and then member name as below
Planet innerPlanner = Planet.Earth;
NOTE
We can declare enumeration in a class or a namespace but not in method.
Thanks for reading my blog, Sharing is caring.