About
In this code snippet, we will see how to use enumerations in C#.
An enum is a data type. To create an enumeration you have to give it a name and define a list of constants that will be available when that enumeration is referenced.
In this code example, we will simulate a key being pressed. The getKey() method will return the key that was pressed. We could just return a string like so “left“. But making an enum with predefined values is much less error-prone than using a string. A misspelled string won’t get caught at compile time meanwhile if you misspell or chose a nonexisting enum an error will occur at compile time.
Let’s have a look at the code below.
Code:
using System;
namespace Enumeration
{
class Program
{
static void Main(string[] args)
{
//Simulate the key being pressesd.
KeyPressed key = getKey();
//Check what key was pressed.
showPressedKey(key);
Console.ReadLine();
}
public static void showPressedKey(KeyPressed key)
{
//If we are unsure what type of enum was given to us we can use this useful bit of code
//to check weather a certain value is defined in our enum type.
if (Enum.IsDefined(typeof(KeyPressed), key))
{
//If so this code executes.
if (KeyPressed.up == key)
{
Console.WriteLine("The up arrow key was pressed.");
}
else if (KeyPressed.down == key)
{
Console.WriteLine("The down arrow key was pressed.");
}
else if (KeyPressed.left == key)
{
Console.WriteLine("The left arrow key was pressed.");
}
else if (KeyPressed.right == key)
{
Console.WriteLine("The right arrow key was pressed.");
}
}
else
{
//Otherwise tell us that the key is undefined.
Console.WriteLine("Undefined key!");
}
}
public static KeyPressed getKey()
{
return KeyPressed.left;
}
//Define the enum and all it's possible values.
public enum KeyPressed
{
up,
down,
left,
right
}
}
}





