What is the Enumeration in C# ??? with Free Notes

What is the Enumeration in C# ???

An Enumeration in C#, or enum, is a distinct value type that consists of a set of named constants called the enumerator list. Enums are used to declare a collection of constants that represent related values.

Syntax – Enumeration in C#

enum EnumName
{
    Value1,
    Value2,
    Value3
}

Example –

using System;

namespace EnumExample
{
    class Program
    {
        enum Days
        {
            Sunday,
            Monday,
            Tuesday,
            Wednesday,
            Thursday,
            Friday,
            Saturday
        }

        static void Main(string[] args)
        {
            Days today = Days.Wednesday;
            Console.WriteLine("Today is: " + today);
            Console.WriteLine("Day number: " + (int)today);
        }
    }
}

Line-by-Line Notes

namespace EnumExample
  • Defines a namespace called “EnumExample” to organize the code and prevent naming conflicts.
enum Days
  • Declares an enumeration named Days.
  • enum: Keyword to declare an enumeration.
  • Days: Name of the enumeration.
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
  • Lists the named constants of the “Days” enumeration. By default, the first enumerator has the value 0, and each subsequent enumerator has a value that is incremented by 1.
Days today = Days.Wednesday;
  • Declares a variable named today of type Days and assigns it the value Days.Wednesday.
  • Days: Data type of the today variable, which is the Days enumeration.
  • today: Name of the variable.
  • Days.Wednesday: Value assigned to the today variable, representing Wednesday.
Console.WriteLine("Day number: " + (int)today);
  • Outputs the underlying integer value of the today variable to the console.
  • (int)today: Casts the today variable to its underlying integer value.
  • "Day number: " + (int)today: Concatenates the string "Day number: " with the integer value of today.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top