Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 41 / 68

Enum (Enumerated Types) Basics

In this lesson you will learn the basics of enums in C#, so a fixed set of options can be referred to by readable names. This is for anyone searching for "C# enum how to use".

C#'s enum creates an enumerated type that represents a fixed set of options. Use it when you want to limit the possible values in advance, the way a traffic light only has red, green, and amber.

The sample code defines three options with enum Color { Red, Green, Blue } and assigns one of them to a variable as Color.Red. Notice how Enum.GetNames(typeof(Color)) lists every name in the enum.

A common stumbling block for beginners is that an enum is backed by integers internally. It reads as a name, but knowing that consecutive integers starting at 0 are assigned behind the scenes saves you from being surprised later.

In real-world development, there is also an advanced use where you tag an enum with the [Flags] attribute and combine several values with bitwise operations.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)