C# - Enum


In C#, an enum is a short form of enumeration. It is a specific type that represents a set of named constant values. Enums are typically used to define a set of related values ​​that have a fixed number of possible choices, such as days of the week, months of the year, or colors.

Why use Enum in C#

There are several advantage or reasons why you might want to use enums in C#:

  1. Better readability and maintainability - Since enums utilise descriptive names to represent values rather than random literals or variables, they make your code more legible and self-documenting. This can make it simpler for future code maintenance and comprehension on the part of other developers.
  2. Compile-time safety - It is provided through enums, which limit the range of possible values that a variable may have. By catching mistakes at compile time rather than at run time, you can reduce the amount of time and effort you spend debugging.
  3. Consistency - Enums make sure that all instances of a particular value have the same underlying representation, which enforces consistency in your code. Your code will become more dependable and help to prevent problems.

 In this example, the MonthofYear enum defines a set of twelve named constants, each of which represents a month of the year.

The following defines an enum for the yearmonths.

enum YearMonths
 {
      January,
      February,
      March,
      April,
      May,
      June,
      July,           
      August,
      September,
      October,
      November,
      December
}

Now access the enum in program.

using System;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(YearMonths.January);
            Console.WriteLine(YearMonths.October);
        }
        enum YearMonths
        {
            January,
            February,
            March,
            April,
            May,
            June,
            July,           
            August,
            September,
            October,
            November,
            December
        }
    }
}

Output

C# Enum
Prev Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#