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

C#

Please contribute by voting. Thanks!
1

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();

Article created: Oct 12 '16. Edited Oct 31 '16.

Your comment

You need to sign up / log in to comment this article

Author

Created by Matt Hamilton [8] Oct 12 '16

Share article

Do you know about

Markdown?

Write an article