C# Enum Underlying integral 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;/*from  w  w  w  .j  a  v a 2  s .  c  o 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;/*ww  w .  j a v 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   ww w . j  ava2  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


/*from w w w. ja  v  a 2 s . c  o m*/
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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor