C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Enum: Enumeration Type

In C#, an enumeration (or enum) is a value type that represents a distinct set of named constants. Enums are useful when you need to represent a set of related values as named constants, making your code more readable and maintainable. In this tutorial, we'll cover the basics of using enums in C#.

  • Defining an enum:

To define an enum, use the enum keyword followed by the name of the enumeration and a set of named constants enclosed in curly braces:

public enum DaysOfWeek
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

By default, the underlying type of an enum is int, and the constants are assigned integer values starting from 0. You can also explicitly specify the underlying type and assign custom values to the constants:

public enum DaysOfWeek : byte
{
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    // ...
}
  • Using enums:

To use an enum, declare a variable of the enum type and assign one of its constants:

DaysOfWeek today = DaysOfWeek.Monday;

You can also use enums in switch statements, comparisons, and method parameters:

public static void PrintGreeting(DaysOfWeek day)
{
    switch (day)
    {
        case DaysOfWeek.Sunday:
            Console.WriteLine("Happy Sunday!");
            break;
        case DaysOfWeek.Monday:
            Console.WriteLine("Happy Monday!");
            break;
        // ...
    }
}

DaysOfWeek today = DaysOfWeek.Monday;
PrintGreeting(today);
  • Converting enums to strings and integers:

You can convert an enum value to a string using the ToString() method or to its underlying integer value using an explicit cast:

DaysOfWeek day = DaysOfWeek.Monday;

string dayString = day.ToString(); // "Monday"
int dayInt = (int)day; // 1
  • Parsing and casting enums:

To convert a string or an integer to an enum value, you can use the Enum.Parse() or Enum.TryParse() methods and an explicit cast:

string dayString = "Monday";
DaysOfWeek day;

if (Enum.TryParse(dayString, out day))
{
    Console.WriteLine("Parsed successfully: " + day);
}
else
{
    Console.WriteLine("Failed to parse.");
}

int dayInt = 1;
day = (DaysOfWeek)dayInt; // DaysOfWeek.Monday

In this tutorial, we've covered the basics of using enums in C#, including defining, using, and converting enums. Enums are a valuable tool for representing sets of related named constants, improving the readability and maintainability of your code.

  1. C# enum examples:

    • Description: Enums in C# provide a way to define a named set of values, making the code more readable and maintainable.
    • Code:
      using System;
      
      public enum DaysOfWeek
      {
          Monday,
          Tuesday,
          Wednesday,
          Thursday,
          Friday,
          Saturday,
          Sunday
      }
      
      class Program
      {
          static void Main()
          {
              DaysOfWeek today = DaysOfWeek.Wednesday;
              Console.WriteLine($"Today is: {today}");
          }
      }
      
  2. Enum in C# with switch statement:

    • Description: Enums are often used with switch statements to handle different cases based on enum values.
    • Code:
      using System;
      
      public enum Season
      {
          Spring,
          Summer,
          Autumn,
          Winter
      }
      
      class Program
      {
          static void Main()
          {
              Season currentSeason = Season.Summer;
      
              switch (currentSeason)
              {
                  case Season.Spring:
                      Console.WriteLine("It's Spring!");
                      break;
                  case Season.Summer:
                      Console.WriteLine("It's Summer!");
                      break;
                  // Handle other seasons...
              }
          }
      }
      
  3. C# flags attribute enum:

    • Description: The Flags attribute allows an enum to be treated as bit fields, enabling bitwise operations.
    • Code:
      using System;
      
      [Flags]
      public enum Permissions
      {
          Read = 1,
          Write = 2,
          Execute = 4
      }
      
      class Program
      {
          static void Main()
          {
              Permissions userPermissions = Permissions.Read | Permissions.Write;
      
              Console.WriteLine($"User has Read and Write permissions: {userPermissions.HasFlag(Permissions.Read | Permissions.Write)}");
          }
      }
      
  4. C# enum underlying type:

    • Description: Enums have an underlying type (default is int), which specifies the storage format of the enum's values.
    • Code:
      using System;
      
      public enum Status : byte
      {
          Active,
          Inactive
      }
      
      class Program
      {
          static void Main()
          {
              Status userStatus = Status.Active;
              Console.WriteLine($"User status: {userStatus}");
          }
      }
      
  5. C# enum parsing and formatting:

    • Description: Enums can be parsed from strings and formatted to strings using the Enum.Parse and Enum.Format methods.
    • Code:
      using System;
      
      public enum Colors
      {
          Red,
          Blue,
          Green
      }
      
      class Program
      {
          static void Main()
          {
              string colorString = "Blue";
              Colors parsedColor = (Colors)Enum.Parse(typeof(Colors), colorString);
              Console.WriteLine($"Parsed Color: {parsedColor}");
      
              string formattedColor = Enum.Format(typeof(Colors), Colors.Green, "G");
              Console.WriteLine($"Formatted Color: {formattedColor}");
          }
      }
      
  6. C# enum to string:

    • Description: Enums can be converted to strings using their ToString method.
    • Code:
      using System;
      
      public enum Sizes
      {
          Small,
          Medium,
          Large
      }
      
      class Program
      {
          static void Main()
          {
              Sizes size = Sizes.Medium;
              Console.WriteLine($"Size: {size.ToString()}");
          }
      }
      
  7. Enum.TryParse in C#:

    • Description: Enum.TryParse is a safer way to parse strings into enums, avoiding exceptions for invalid values.
    • Code:
      using System;
      
      public enum Months
      {
          January,
          February,
          March
      }
      
      class Program
      {
          static void Main()
          {
              string monthString = "February";
              if (Enum.TryParse(monthString, out Months parsedMonth))
              {
                  Console.WriteLine($"Parsed Month: {parsedMonth}");
              }
              else
              {
                  Console.WriteLine("Invalid month string");
              }
          }
      }
      
  8. C# enum to int conversion:

    • Description: Enums can be converted to their underlying integral type (default is int).
    • Code:
      using System;
      
      public enum Grades
      {
          A = 90,
          B = 80,
          C = 70
      }
      
      class Program
      {
          static void Main()
          {
              Grades studentGrade = Grades.B;
              int gradeValue = (int)studentGrade;
              Console.WriteLine($"Grade Value: {gradeValue}");
          }
      }