Type.GetEnumName() Method in C#


The Type.GetEnumName() method in C# returns the name of the constant that has the specified value, for the current enumeration type.

Syntax

Following is the syntax −

public virtual string GetEnumName (object val);

Above, Val is the value whose name is to be retrieved.

Example

Let us now see an example to implement the Type.GetEnumName() method −

using System;
public class Demo {
   enum Vehicle {Car, Bus, Bike}
   public static void Main(){
      Vehicle v = Vehicle.Bike;
      Type type = v.GetType();
      string str = type.GetEnumName(v);
      Console.WriteLine("GetEnumName() to return the constant name = " + str);
   }
}

Output

This will produce the following output −

GetEnumName() to return the constant name = Bike

Example

Let us now see another example to implement the Type.GetEnumName() method −

using System;
public class Demo {
   enum Vehicle {Car, Bus, Bike}
   public static void Main(){
      try {
         Vehicle v = Vehicle.Bike;
         Type type = typeof(string);
         string str = type.GetEnumName(v);
         Console.WriteLine("GetEnumName() to return the constant name = " + str);
      }
      catch (ArgumentException e){
         Console.WriteLine("Not an enum!");
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}

Output

This will produce the following output −

Not an enum!
System.ArgumentException

Updated on: 21-Apr-2020

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements