access enum c# code example

Example 1: c# enum

// ---------------------- HOW TO USE ENUMS? ----------------------- //

// How to create?

public enum Colors   // It needs to be defined at the namespace level (outside any class)! 
{
	red = 1,
    green = 2,
    blue = 3,
    white = 4,
    black = 5

}

// How to get the values?

var itemRed = Colors.red;

Console.WriteLine((int)itemRed);  // Using casting to convert to int


// How to get the keys?

var itemX = 4;

Console.WriteLine((Colors)itemX);  // Using casting to convert to Colors
 

// How to convert enums to strings? 

var itemBlue = Colors.blue;

Console.WriteLine(itemBlue.ToString());


// How to convert strings to enums? 

var colorName = "green";

var enumName = (Colors)Enum.Parse(typeof(Colors), colorName);

Console.WriteLine(enumName);       // To see the key
Console.WriteLine((int)enumName);  // To see the value

Example 2: C# enum

enum CellphoneBrand { 
        Samsung,
        Apple,
  		LG,
  		Nokia,
  		Huawei,
  		Motorola
    }

Example 3: how to retrive an enum string value instead of number in c# controller

enum WeekDays
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Console.WriteLine(Enum.GetName(typeof(WeekDays), 4));

Console.WriteLine("WeekDays constant names:");

foreach (string str in Enum.GetNames(typeof(WeekDays)))
            Console.WriteLine(str);

Console.WriteLine("Enum.TryParse():");

WeekDays wdEnum;
Enum.TryParse<WeekDays>("1", out wdEnum);
Console.WriteLine(wdEnum);