C# | Type.GetEnumName() Method
Last Updated :
04 Sep, 2021
Type.GetEnumName(Object) Method is used to return the name of the constant which has the specified value for the current enumeration type.
Syntax:
public virtual string GetEnumName (object value);
Here, it takes the value whose name is to be retrieved.
Return Value: This method returns the name of the member of the current enumeration type which has the specified value. If no such constant is found then it will return null.
Exceptions:
- ArgumentException: If the current type is not an enumeration or value is neither of the current type nor does it have the same underlying type as the current type.
- ArgumentNullException: If value is null.
Below programs illustrate the use of the above-discussed method:
Example 1:
csharp
using System;
using System.Globalization;
using System.Reflection;
class GFG {
enum ABC {A, B, C}
public static void Main()
{
try {
ABC a = ABC.A;
Type type = a.GetType();
string obj = type.GetEnumName(a);
Console.WriteLine( "Name of constant is: " + obj);
}
catch (ArgumentNullException e)
{
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
Name of constant is: A
Example 2: For ArgumentException
csharp
using System;
using System.Globalization;
using System.Reflection;
class GFG {
enum ABC {A, B, C}
public static void Main()
{
try {
ABC a = ABC.A;
Type type = typeof ( int );
string obj = type.GetEnumName(a);
Console.WriteLine( "Name of constant is: " + obj);
}
catch (ArgumentNullException e)
{
Console.WriteLine( "value is null. " );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
catch (ArgumentException e)
{
Console.WriteLine( "The current type is not an Enumeration." );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
The current type is not an Enumeration.
Exception Thrown: System.ArgumentException
Example 3: For ArgumentNullException
csharp
using System;
using System.Globalization;
using System.Reflection;
class GFG {
enum ABC {A, B, C}
public static void Main()
{
try {
ABC a = ABC.A;
Type type = typeof ( int );
string obj = type.GetEnumName( null );
Console.WriteLine( "Name of constant is " + obj);
}
catch (ArgumentNullException e)
{
Console.WriteLine( "value is null. " );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
catch (ArgumentException e)
{
Console.WriteLine( "The current type is not an Enumeration." );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
value is null.
Exception Thrown: System.ArgumentNullException
Reference:
Share your thoughts in the comments
Please Login to comment...