Order Now

C# Enum

shape image

C# Enum

C# Enum


C# Enum: A Guide to Enumerations in C#

An enumeration, commonly known as an "enum", is a value type in C# that is used to represent a set of named values. It is used to define a group of named constant values that can be easily referenced within your code. Enumerations are a convenient way to represent a collection of related values, as opposed to using multiple constant values or variables.

Here is the basic syntax for declaring an enum in C#:
enum EnumName {
   EnumValue1,
   EnumValue2,
   EnumValue3,
   ...
}

Each value in the enum is separated by a comma, and each value has a unique name within the enum. By default, the first value in an enum is assigned the value 0, and each subsequent value is assigned the value of the previous value plus one. 

However, you can also explicitly set the values of each value in the enum:

enum EnumName {
   EnumValue1 = 1,
   EnumValue2 = 2,
   EnumValue3 = 4,
   ...
}

Example with Switch Statement

You can use an enum just like any other value type in C#. Here is an example of how to use an enum in a switch statement:


Color myColor = Color.Red;

switch (myColor) {
   case Color.Red:
      Console.WriteLine("The color is red");
      break;
   case Color.Green:
      Console.WriteLine("The color is green");
      break;
   case Color.Blue:
      Console.WriteLine("The color is blue");
      break;
}

enum Color { Red, Green, Blue };

In this example, the myColor variable is assigned the value of Color.Red. The switch statement then tests the value of myColor and executes the appropriate case based on the value.

Use an enum as a type for a property or method parameter:
SetColor(Color.Green);

static void SetColor(Color color)
{
    Console.WriteLine("The color is: " + color);
}

enum Color { Red, Green, Blue };

In this example, the SetColor method accepts a parameter of type Color. You can pass any value from the Color enum as an argument when calling the method.

Enumerations provide a convenient way to represent a set of related values in C#. They are easy to use and can greatly improve the readability of your code. By using enums, you can simplify your code and make it easier to maintain.

Post a Comment

© Copyright 2023 ZakirDev

Order Form

I will contact you on WhatsApp.

Order now