![]() |
VOOZH | about |
Enumeration (enum) in C# is a special value type that defines a set of named constants. It improves code readability by giving meaningful names to numeric values.
Example: Enum of Days in a week
enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
Enumeration is declared using the enum keyword directly inside a namespace, class or structure.
Example: Using Enumeration within the same class to store the book with their index.
Book: Java at Index:4 Book: Python at Index:3 Book: Kotlin at Index:2 Book: Javascript at Index:1 Book: cSharp at Index:0
Explanation: In the above example we create a enum (Enumeration) to declare the name of books and access their index value which is starting from the 0 in the enum and type cast the value to get the values in numeric from.
By default, the first member starts at 0, but you can assign custom values.
Example: Another example of an enum is to show the month name with its default value.
The value of jan in month enum is 0 The value of feb in month enum is 1 The value of mar in month enum is 2 The value of apr in month enum is 3 The value of may in month enum is 4
Explanation: In the above code we create a enum with month name, its data members are the name of months like jan, feb, mar, apr, may. Then print the default integer values of these enums. An explicit cast is required to convert from enum type to an integral type.
Example: Using enum to find the shapes to find their perimeter.
Explanation: In the example, an enum Shapes is defined with Circle = 0 and Square = 1. The class Perimeter has a method peri() that takes one parameter for side/radius and another (0 or 1) to identify the shape using Shapes.Circle or Shapes.Square. If the value is 0, it’s a circle; otherwise, it’s a square.
The default value of first enum member is set to 0 and it increases by 1 for the further data members of enum. However, the user can also change these default value.
enum days {
day1 = 1,
day2 = day1 + 1,
day3 = day1 + 2
.
.}
By default, enum values are of type int, but you can change them to byte, short, long, etc.
Example: Custom value initialization in enum.
Note: Now, if the data member of the enum member has not been initialized, then its value is set according to the rules stated below:
Example: Changing the type of enum’s data member
The electric switch is ON
Explanation: By default the base data type of enumerator in C# is int. However, the user can change it as per convenience like byte, byte, short, short, int, uint, long, etc In this example, we change the data type as byte.