C# Enumerations

In this Tutorial You will learn how to create Enumeration in C#. This is a syntax sugar that helps to store informations in short and meaningful way. It makes code more readable and secure the Fields from invalid inputs. An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.

Enums

Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. They are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.

 

enum Syntax:


enum <enum_name> { enumeration list };

 

This can be written i one line as i will show you later.

Lats take a look at example i came up with. In this Program i have an Enemy class that contains type of enemy and behaviour. For both of the properties i create a enum that list all possible options. This way I’m sure that constructor will pass only the type i listed in Class declaration.

 enum Behaviour { Agressive, Neutral, Friendly }
 enum Type { Skeleton, Vampire, Ghoul }
 class Program
 {
   static void Main(string[] args)
   {
     Enemy[] enemies= new Enemy[3];
     enemies[0] = new Enemy(Type.Ghoul, Behaviour.Agressive);
     enemies[1] = new Enemy(Type.Skeleton, Behaviour.Neutral);
     enemies[2] = new Enemy(Type.Vampire, Behaviour.Friendly);

     foreach (Enemy e in enemies)
     {
        e.Print();
     }
     Console.ReadLine();
   }
 }
class Enemy
 {
   Type type;
   Behaviour behaviour; 

   public Enemy(Type _type,Behaviour _behaviour)
   {
     this.type = _type;
     this.behaviour = _behaviour;
   }
public void Print()
   {
      Console.WriteLine(behaviour.ToString()+" "+ type.ToString());
   }

 }

Enums are using integer values as a default value. We can convert the Selected type to an integer. We can overwrite the Print method like this.


public void Print()
{
Console.WriteLine((int)behaviour+" "+ (int)type);
}

The output will be

0   2

1   0

2   1

 

Enums allows to assign values to the elements in the definition. Values of elements after the one that have assigned value will be incremented by one

//Result values: 4,5,6
enum Behaviour { Agressive=4, Neutral, Friendly }
// Result, values 0,7,8
enum Type { Skeleton, Vampire=7, Ghoul }

You can change the variable type, from default integer to almost  anything else.

enum Behaviour : Byte { Agressive=12, Neutral, Friendly }

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

 

This post covered the most basic functionalities of enum keyword. I encourage you to implement some of the functions to your code, this can make it easier to read and faster to write. Stay Awesome!