C# Enum GetNames Method


The GetNames() returns the array of names of the constants in the Enumeration.

The following is the enum.

enum Stock { Watches, Books, Grocery };

To get the array of names, use the GetNames() and loop through as shown below −

foreach(string s in Enum.GetNames(typeof(Stock))) {
}

Let us see the complete example now.

Example

 Live Demo

using System;
class Demo {
   enum Stock { Watches, Books, Grocery };
   static void Main() {
      Console.WriteLine("The value of first stock category = {0}",Enum.GetName(typeof(Stock), 0));
      Console.WriteLine("The value of second stock category = {0}",Enum.GetName(typeof(Stock), 1));
      Console.WriteLine("The value of third stock category = {0}",Enum.GetName(typeof(Stock), 2));
      Console.WriteLine("All the categories of stocks...");
      foreach(string s in Enum.GetNames(typeof(Stock))) {
         Console.WriteLine(s);
      }
   }
}

Output

The value of first stock category = Watches
The value of second stock category = Books
The value of third stock category = Grocery
All the categories of stocks...
Watches
Books
Grocery

Updated on: 23-Jun-2020

698 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements