C# Enum Value

In this chapter you will learn:

  1. Assign int value to enumerations
  2. Enumerations Initialization with calculation
  3. Output enum element value
  4. Loop through the enum data type
  5. 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:

  1. Enum Underlying integral value
  2. How to change enum backend value
  3. Example for how to create an enum type based on byte type
  4. enum type conversion
  5. How to compare two enum values
  6. How to format enum value
Home »
  C# Tutorial »
    C# Types »
      C# Enum
C# Enums
C# Enum Value
C# Enum Underlying integral value
C# Flag Enum