C# Enumerations

C# Code Snippets Enumerations
Share:

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
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger