C# Enum Value
In this chapter you will learn:
- Assign int value to enumerations
- Enumerations Initialization with calculation
- Output enum element value
- Loop through the enum data type
- Get all stats for an enum: Enum.GetValues()
Assign int value to enumerations
/*from w w w. jav a 2 s .com*/
using System;
enum Values
{
A = 1,
B = 5,
C = 3,
D = 42
}
class MainClass
{
public static void Main()
{
Values v = (Values) 2;
int ival = (int) v;
}
}
The code above generates the following result.
Enumerations Initialization with calculation
Enumerations Initialization with calculation
using System;//from www . ja v a 2 s. co m
enum Values
{
A = 1,
B = 2,
C = A + B,
D = A * C + 33
}
class MainClass
{
public static void Member(Values value)
{
Console.WriteLine(value);
}
public static void Main()
{
Values value = 0;
Member(value);
}
}
The code above generates the following result.
Output enum element value
Output enum element value
using System;/*from w w w .j a va 2 s . c om*/
enum Color
{
red,
green,
yellow
}
public class MainClass
{
public static void Main()
{
Color c = Color.red;
Console.WriteLine("c is {0}", c);
}
}
The code above generates the following result.
Loop through the enum data type
Loop through the enum data type
using System; //from w ww. j a va 2 s .co m
class MainClass {
enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturaday,Sunday };
public static void Main() {
Week i;
for(i = Week.Monday; i <= Week.Sunday; i++)
Console.WriteLine(i + " has value of " + (int)i);
}
}
The code above generates the following result.
Get all stats for an enum: Enum.GetValues()
Get all stats for an enum: Enum.GetValues()
using System;// w w w . j av a2s . co m
enum EmployeeType : byte
{
Manager = 10,
Programmer = 1,
Contractor = 100,
Developer = 9
}
class MainClass
{
public static void Main(string[] args)
{
Array obj = Enum.GetValues(typeof(EmployeeType));
Console.WriteLine("This enum has {0} members:", obj.Length);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Enum Underlying integral value
- How to change enum backend value
- Example for how to create an enum type based on byte type
- enum type conversion
- How to compare two enum values
- How to format enum value