C# Enum Underlying integral value
In this chapter you will learn:
- 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
Description
Each enum member has an underlying integral value.
The constants 0, 1, 2... are automatically assigned, in the declaration order of the enum members.
You may specify an alternative integral type, as follows:
public enum Direction : byte { Left, Right, Top, Bottom }
You may also specify an explicit underlying value for each enum member:
public enum Direction : byte { Left=1, Right=2, Top=10, Bottom=11 }
Syntax
If you have to change the backend numeric type for an enum type, here is the syntax:
enum EnumType: IntegerTypeName{
...
}
Example 1
In the following code we create an enum type based on byte type.
using System;/* w w w.j a va 2s .co m*/
enum WeekDay : byte
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
class Test
{
static void Main()
{
WeekDay day = WeekDay.Monday;
WeekDay day2 = WeekDay.Tuesday;
Console.WriteLine(day > day2);
if (day == WeekDay.Monday)
{
Console.WriteLine("it is monday");
}
}
}
The code above generates the following result.
Example 2
An enum value is convertable to its underline numeric value.
using System;//w w w . j av a 2 s.c om
enum WeekDay
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
class Test
{
static void Main()
{
int i = (int)WeekDay.Monday;
Console.WriteLine(i);
//We can even convert integer back to enum value.
WeekDay day = (WeekDay)2;
Console.WriteLine(day);
}
}
The output:
Example 3
using System;/*from w w w.j a v a 2 s. c o m*/
enum EmployeeType : byte
{
Manager = 10,
Programmer = 1,
Contractor = 100,
Developer = 9
}
class MainClass
{
public static void Main(string[] args)
{
EmployeeType Joe = EmployeeType.Developer;
EmployeeType Fran = EmployeeType.Programmer;
if(Joe < Fran)
Console.WriteLine("Joe's value is less than Fran's");
else
Console.WriteLine("Fran's value is less than Joe's");
}
}
The code above generates the following result.
Example 4
/*w w w . j av a2 s . c om*/
using System;
enum EmployeeType : byte
{
Manager = 10,
Programmer = 1,
Contractor = 100,
Developer = 9
}
class MainClass
{
public static void Main(string[] args)
{
EmployeeType fred;
fred = EmployeeType.Developer;
Console.WriteLine("You are a {0}", fred.ToString());
Console.WriteLine("Hex value is {0}", Enum.Format(typeof(EmployeeType), fred, "x"));
Console.WriteLine("Int value is {0}", Enum.Format(typeof(EmployeeType), fred, "D"));
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- What is flag enum
- How to create and use flag enum
- How to check the combination of flag enum
- Using Bit flags when declaring the enum