Enums in c# programming example

C# enum: Enum data type is used when we have some fixed set of values, which we want to send as options for programmer to call from their function, for example, if we accept only gif and jpg file in our function, we can create a enum like example below.

enum EventState
{
    Gif = 1,
    Jpg = 2   
}

In this tutorial we learn about enum in C#

What is enum in C# .Net (Enumerator)

Enum is a value type in .net data type, Enum is an abstract class that has some static methods to work with enum. Before we see some enum example, let's take a look at the methods of System.Enum.

C# enum methods example

  • GetName

    Gets the name of the constant in the specified enumeration

  • GetNames

    Returns a string array of constant names

  • GetValues

    Returns an array of constant values

Create a enum C# Example

This is how you can create a enum in C#, you can declare a enum as protected, private, public

enum EventState
{
    Initiated = 1,
    Started = 2,
    Closed = 3,
    Canceled = 4
}

Enum GetNames Example
Here we see how to use enum (enumeration) in our c# code

foreach (string str in Enum.GetNames(typeof(EventState)))
{
    Console.WriteLine(str);
}
Enum GetValues Example
foreach (int i in Enum.GetValues(typeof(EventState)))
{
    Console.WriteLine(i);
}
//this will print the number 2
Console.WriteLine((int)EventState.Started);
            
// this will print string "Started"
Console.WriteLine(EventState.Started);
}
C# Enum Array Example

You can define a enum in c# as Array Index

enum ColorSignal
{
    red,
    white,
    blue,
    green,
    yellow,
    orange,
    grey
}

Now we write an C# program with an array that is indexed with enum values. here you notice how to cast an enum to an int.

void EnumTest()
{
    int[] _array = new int[(int)ColorSignal.white];            
}
Iterate a enum c#

we can iterate or loop through an enum items using foreach loop or for loop, take a look at example below

foreach (string s in Enum.GetNames(typeof(ColorSignal)))
    {
        Console.WriteLine(s);
    }
Read value from enum in c#

we can also read value from enum like this way

Console.WriteLine(ColorSignal.green);
// this will print string value - green

Console.WriteLine((int)ColorSignal.green);
// this will print int value - 3
enum c# as parameter

we can pass C# enum as parameter in any method, and we can that enum as string, also can get the enum integer value, take a look at the example below.

public  void AddColor(ColorSignal color)
{
    Console.WriteLine(color.ToString()); // orange

    Console.WriteLine(color); // orange

    Console.WriteLine((int)color); // 6
}

// call the method and pass enum as parameter
AddColor(ColorSignal.orange);

You may also check How to convert enum to generic list type

 
C# Enums Example
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course