Getting the name of the Enumeration Constant having Specified value in C#

Enum.GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value.

Syntax:

public static string GetName (Type enumType, object value);

Parameters:



  • enumType: It is an enumeration type.
  • value: It is the value of a particular enumerated constant in terms of its underlying type.

Returns: It is a string containing the name of the enumerated constant in enumType whose value is the value or null if no such constant is found.

Exceptions:

  • ArgumentNullException: If the enumType or value is null.
  • ArgumentException: If the enumType is not an Enum or value is neither of type enumType nor does it have the same underlying type as enumType.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the
// Enum.GetName(Type, Object) Method
using System;
  
enum Animals { Dog,
               Cat,
               Cow,
               Monkey };
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // using the method
        Console.WriteLine("2nd value is {0}", Enum.GetName(typeof(Animals), 1));
        Console.WriteLine("4th value is {0}", Enum.GetName(typeof(Animals), 3));
    }
}

chevron_right


Output:

2nd value is Cat
4th value is Monkey

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.