C# Enum2 min read

Enum is also known as enumeration that consists of a set of named integral constants. In C#, enumerations are value data types. The keyword enum is used to define these data types.

The is mainly used to assign the names or string that makes the code more maintainable and readable. For example, we can create an enum for seasons (spring, summer, autumn, winter), or for days(Monday, Tuesday, ….), etc.

The constant in it is the fixed set of constants and is also known as an enumerator. Enum can also be traversed.

Syntax of enums

enum enum_name{const1, const2, ....... };

  • enum_name: Name of the enum given by the user.
  • const1, const2 : These are the value of type enum_name, separated by comma.

Let us see an example to define enum.

enum season { spring, summer, autumn, winter };

The above is the enum for the season, spring, summer, autumn and winter are the types of the season and by default, the value starts in increasing order from zero such as spring is 0, summer is 1, autumn is 2 and winter is 3.


Example 1: C# program for enum

Output:

Spring: 0
Winter: 3

As you can see that the default numbers assigned to the constant are shown according to the access. Spring is first on the list so it is 0 and And Winter is at fourth on the list so it is 3 (n-1, starts at 0).


Example 2: C# program for enum to change the index

We write a program to change the default indexing of constants in an enum.

Output:

Spring: 10
Summer: 11
Winter: 13

Now we assign 10 to spring in the list, and from here the increment starts summer becomes 11, and so on. Also, can be seen in the output.


Example 3: C# program for enum use of getValues()

We will use getValues and get all the values present in the enum of the season.

Output:

Spring
Summer
Autumn
Winter


MORE

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More

Keith Number Program in C++

In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you …
Read More

Singly linked list Program C++

In this tutorial, we will write a C++ program to implement singly linked list. In this program, we will create a separate function for each …
Read More

Fascinating Number Program in C

In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through …
Read More

Peterson Number in C

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C. What is Peterson Number? …
Read More

Peterson Number in C++

In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number …
Read More