Enums in C# – Creating, looping, casting and counting

Home » Enums in C# – Creating, looping, casting and counting

A few features of the enum concept in C#…

Create enum

public enum Names
    Robert, //Will get 0 as value
    Julia, //Will get 1 as value
    Matt = 3 //Will be forced to 3

Enumerating / looping Enums in C

foreach (Names item in Enum.GetValues(typeof(Names)))
    // ...

Cast int to enum

Cast int to enum (name will be Matt):

Names name = (Names)3;

Check if cast is possible:

if (Enum.IsDefined(typeof(Names), 3))

Cast enum to int

Cast enum to int-value (value will be 3):

int value = (int)Names.Matt;

Number of items

Get number of names in enum (will return 3):

var namesCount = Enum.GetNames(typeof(Names)).Length;

Get number of distinct values (will return 3):

var valuesCount = Enum.GetValues(typeof(Names)).Cast<Names>().Distinct().Count();

High and low values

Get the items with the highest and lowest values:

var maxValueItem = Enum.GetValues(typeof(Names)).Cast<Names>().Max();
var minValueItem = Enum.GetValues(typeof(Names)).Cast<Names>().Min();