Enums

Published Apr 22, 2023Updated Apr 27, 2023
Contribute to Docs

An enum, or enumeration type, is a set of named labels that each represent a number.

Syntax

By default, each entry in an enum is assigned a zero-indexed value.

enum NinjaTurtle {
Leonardo, // 0
Michelangelo, // 1
Donatello, // 2
Raphael // 3
}
Console.WriteLine((int)NinjaTurtle.Raphael == 3); // Prints "True"

However, specific number values can also be assigned.

enum BreadCount {
Dozen = 12,
BakersDozen = 13,
Gross = 144,
GreatGross = 1728
}

Example

The following example uses an enum to identify whether a given place is a city, country, or planet.

using System.Collections.Generic;
public enum PlaceType {
City,
Country,
Planet,
}
public class Place {
public string name { get; set; }
public PlaceType type { get; set; }
public Place(string n, PlaceType t) {
name = n;
type = t;
}
}
public class Example {
public static void Main() {
List<Place> places = new List<Place>();
places.Add(new Place("Tokyo", PlaceType.City));
places.Add(new Place("Canada", PlaceType.Country));
places.Add(new Place("Jupiter", PlaceType.Planet));
}
}

Codebyte Example

The following example uses an enum to classify different types of log messages.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn C# on Codecademy