C# Enumerations

C# Code Snippets Enumerations


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.


[amp-gist id=”75ba84a46d23ace8bc20c7a5624858a3″]

Resulting output:


Leave a Reply

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

The reCAPTCHA verification period has expired. Please reload the page.
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