CodeBlanks Logo Icon CodeBlanks

Enum values

C# course · Beginner · Lesson 101/116

Learn to access enum members and their values.

Underlying integer values

Each enum member carries an integer value behind the scenes. By default the first member is 0 and each following member is one greater. You can read this value with an (int) cast.

For example, in enum Day { Mon, Tue, Wed }, Day.Mon is 0, Day.Tue is 1 and Day.Wed is 2. The expression (int)Day.Tue gives 1. This lets you use enum values by their numeric counterparts.

Explicit value assignment

You can give enum members explicit integer values. Use the = sign to set the value; following members continue to increment automatically. This is useful for database codes or protocol constants that need specific numbers.

For example, enum Level { Low = 1, Mid = 2, High = 3 } sets each value explicitly. Or in enum Code { A = 10, B, C }, A=10, B=11, C=12; after an explicit value, auto-increment continues.

Choosing the underlying type

The underlying type of an enum is int by default. You can pick other integer types like byte, short or long by specifying the type after a colon in the declaration.

For example, enum Code : byte { A, B, C } makes the underlying type byte, so values stay in the 0-255 range. This is useful for memory savings or compatibility with external systems. In most cases the default int is fine.

Exercise Print the priority as int

Define an enum called Priority with members Low = 1, Normal = 2, High = 3. In Main, assign Priority.High to p as Priority p = Priority.High; and print (int)p with Console.WriteLine.

Show example solution
Define enum Priority { Low = 1, Normal = 2, High = 3 }, then add Priority p = Priority.High; and Console.WriteLine((int)p);
Example solution:
using System;

enum Priority { Low = 1, Normal = 2, High = 3 }

class Program
{
    static void Main()
    {
        Priority p = Priority.High;
        Console.WriteLine((int)p);
    }
}

Test yourself

  1. What is the value of Day.Tue?

    enum Day { Mon, Tue, Wed }
    • 0
    • 2
    • 1
    • 10
    Show answer

    1 — Correct! Tue is the second member, so its value is 1.

  2. Enum with explicit values

    enum Level { Low = 1, Mid = ____, High = 3 }
    Show answer
    enum Level { Low = 1, Mid = 2, High = 3 }
  3. Match the enum declaration with its values

    enum E {A, B}
    A=0, B=1
    enum E {A=10, B}
    A=10, B=11
    enum E {A=1, B=2}
    A=1, B=2

All lessons in Beginner