Enum.GetNames in C#

The Enum.GetNames() method in C# retrieves an array of the names of constants in a specified enumeration. This method is useful when you need to dynamically access or display all the values defined in an enum without hardcoding them.

Syntax

Following is the syntax for the Enum.GetNames() method −

public static string[] GetNames(Type enumType)

Parameters

  • enumType − The System.Type of the enumeration whose names you want to retrieve.

Return Value

Returns a string[] array containing the names of the constants in the specified enumeration, ordered by their underlying values.

Using Enum.GetNames() with Simple Enums

Example

using System;

class Demo {
    enum Vehicle {
        Car,
        Motorbike,
        Truck,
    };
    static void Main() {
        // display the enum names
        foreach (string res in Enum.GetNames(typeof(Vehicle)))
            Console.WriteLine(res);
    }
}

The output of the above code is −

Car
Motorbike
Truck

Using Enum.GetNames() with Custom Values

The method works with enums that have custom underlying values as well −

Example

using System;

class Demo {
    enum Priority {
        Low = 1,
        Medium = 5,
        High = 10,
        Critical = 20
    };
    
    static void Main() {
        Console.WriteLine("Priority levels:");
        string[] names = Enum.GetNames(typeof(Priority));
        
        foreach (string name in names) {
            Console.WriteLine($"{name} = {(int)Enum.Parse(typeof(Priority), name)}");
        }
    }
}

The output of the above code is −

Priority levels:
Low = 1
Medium = 5
High = 10
Critical = 20

Practical Use Case with Dynamic Menu

Here's a practical example showing how Enum.GetNames() can be used to create a dynamic menu system −

Example

using System;

class MenuDemo {
    enum MenuOptions {
        NewFile,
        OpenFile,
        SaveFile,
        Exit
    };
    
    static void Main() {
        Console.WriteLine("Available Menu Options:");
        string[] menuNames = Enum.GetNames(typeof(MenuOptions));
        
        for (int i = 0; i 

The output of the above code is −

Available Menu Options:
1. NewFile
2. OpenFile
3. SaveFile
4. Exit

Total options: 4

Key Points

  • The names are returned in the order of their underlying values, not declaration order.

  • The method returns a new array each time it's called, so modifying the returned array doesn't affect the enum.

  • Works with any enum type, regardless of the underlying data type (int, byte, long, etc.).

Conclusion

The Enum.GetNames() method provides a convenient way to retrieve all constant names from an enumeration as a string array. It's particularly useful for creating dynamic menus, validation lists, or any scenario where you need to programmatically work with enum values without hardcoding them.

Updated on: 2026-03-17T07:04:35+05:30

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements