C# - Enum.GetValues() Method with Example

In this tutorial, we will learn about the C# Enum.GetValues() method with its definition, usage, syntax, and example. By Nidhi Last updated : March 29, 2023

C# Enum.GetValues() Method

The Enum.GetValues() method is used to Retrieves an array of the values of the constants in the specified enum.

Syntax

Array Enum.GetValues(Type enumType);

Parameter(s)

Here we pass an instance of a specified enum.

Return Value

This method returns an array of the values of the constants in the specified enum.

Exception(s)

  • System.ArgumentException
  • System.ArgumentNullException

C# Example of Enum.GetValues() Method

The source code to demonstrate the GetValues() method of Enum class is given below. The given program is compiled and executed successfully.

using System;

class Sample {
  enum Directions {
    EAST = 0, WEST = 1, NORTH = 2, SOUTH = 3
  };

  //Entry point of Program
  static public void Main() {
    Console.WriteLine("Values of Directions:");
    foreach(var val in Enum.GetValues(typeof (Directions))) {
      Console.WriteLine("{0,3}     0x{0:X8}     {1}", (int) val, ((Directions) val));
    }
  }
}

Output

Values of Directions:
  0     0x00000000     EAST
  1     0x00000001     WEST
  2     0x00000002     NORTH
  3     0x00000003     SOUTH
Press any key to continue . . .

C# Enum Class Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.