Classes

C# Enums

Using Enums

C# enums define named constants with underlying types.

What is an Enum?

An enum (short for enumeration) in C# is a value type defined by a set of named constants of the underlying integral numeric type. Enums are used to create a collection of related constants, making the code more readable and maintainable. By default, the underlying type of each element in the enum is int, starting at zero and incrementing by one.

Defining and Using Enums

To define an enum, use the enum keyword followed by a name and a list of values enclosed in curly braces. You can access the values of an enum using the dot syntax. Below is an example of defining and using an enum in C#:

Specifying an Enum's Underlying Type

By default, an enum's underlying type is int. However, you can specify another integral type such as byte, sbyte, short, ushort, uint, long, or ulong. This can be useful when memory consumption is a concern or when interfacing with code expecting an exact size.

Assigning Values to Enum Members

You can assign specific values to enum members. This is useful when the values need to match certain specifications, such as protocol messages or file formats. If a value is not specified, it continues incrementing from the last specified value.

Using Enums in Switch Statements

Enums are often used in switch statements to handle different outcomes based on the enum value. This can make the code more organized and easier to understand.

Converting Enums to Strings and Vice Versa

Enums can be easily converted to strings for display purposes and can also be parsed from strings. This is useful for serializing or deserializing data.