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
4.44
9
enum Season
{
Spring,
Summer,
Autumn,
Winter
}
Thank you!
9
0
0
7
enum Level
{
Low,
Medium,
High
}
Level myVar = Level.Medium;
Console.WriteLine(myVar);
Thank you!
7
0
3.57
7
enum Level
{
Low,
Medium,
High
}
Thank you!
7
0
3.63
8
enum Season
{
Spring,
Summer,
Autumn,
Winter
}
Thank you!
8
0
4.14
7
enum CellphoneBrand {
Samsung,
Apple,
LG,
Nokia,
Huawei,
Motorola
}
Thank you!
7
0
4.33
6
enum Level
{
Low,
Medium,
High
}
//You can access enum items with the dot syntax:
Level myVar = Level.Medium;
Console.WriteLine(myVar);
Thank you!
6
0
Are there any code examples left?
New code examples in category C#
-
C# 2022-03-27 22:40:23 c# movement script
-
C# 2022-03-27 22:15:17 Delete last modification on EntityFramework Core
-
C# 2022-03-27 22:15:02 file.create folder c#
-
C# 2022-03-27 19:25:04 Error inflating class android.support.constraint.ConstraintLayout
-
C# 2022-03-27 19:15:02 top down shooting in unity 2D
-
C# 2022-03-27 18:50:02 c# remove invalid directory characters
-
C# 2022-03-27 18:30:07 how to use K2 games Games parallax background
-
C# 2022-03-27 18:25:10 c# replace crlf
-
C# 2022-03-27 18:25:09 keycode for left mouse click unity