how to use enum in c# - Search
Open links in new tab
  1. Enums in C# are a way to define a set of named integral constants that make your code more readable and maintainable. They are particularly useful when you have a fixed set of related constants.

    Basic Enum Declaration

    To declare an enum, use the enum keyword followed by the name of the enum and its members.

    enum Level
    {
    Low,
    Medium,
    High
    }

    You can then use the enum like this:

    Level myVar = Level.Medium;
    Console.WriteLine(myVar); // Output: Medium

    Enum with Custom Values

    By default, the first member of an enum has the value 0, and each subsequent member is incremented by 1. You can also assign custom values to enum members.

    enum Months
    {
    January, // 0
    February, // 1
    March = 6, // 6
    April, // 7
    May // 8
    }

    To get the integer value of an enum member:

    int monthValue = (int)Months.April;
    Console.WriteLine(monthValue); // Output: 7

    Enum in a Switch Statement

    Enums are often used in switch statements to handle different cases based on the enum value.

    enum Level { Low, Medium, High }

    Level myVar = Level.Medium;

    switch (myVar)
    {
    case Level.Low:
    Console.WriteLine("Low level");
    break;
    case Level.Medium:
    Console.WriteLine("Medium level");
    break;
    case Level.High:
    Console.WriteLine("High level");
    break;
    }
    Feedback
    Kizdar net | Kizdar net | Кыздар Нет
  1. Some results have been removed