C# | Type.GetEnumNames() Method
Last Updated :
31 Aug, 2021
Type.GetEnumNames() Method is used to return the names of the members of the current enumeration type.
Syntax:
public virtual string[] GetEnumNames ();
Returns: This method returns an array which contains the names of the members of the enumeration.
Exception: This method will give ArgumentException if the current type is not an enumeration.
Below programs illustrate the use of the above-discussed method:
Example 1:
C#
using System;
using System.Globalization;
using System.Reflection;
class GFG {
enum ABC { A,
B,
C,
D,
E,
F }
public static void Main()
{
try {
ABC a = ABC.A;
Type type = a.GetType();
string [] obj = type.GetEnumNames();
Console.WriteLine( "The constants are as follow :-" );
for ( int i = 0; i < obj.Length; i++)
Console.Write( "{0} " , obj[i]);
}
catch (ArgumentException e)
{
Console.Write( "The current type is not an enumeration." );
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
The constants are as follow :-
A B C D E F
Example 2: For ArgumentException
C#
using System;
using System.Globalization;
using System.Reflection;
class GFG {
enum ABC { A,
B,
C,
D,
E,
F }
public static void Main()
{
try {
Type type = typeof ( int );
string [] obj = type.GetEnumNames();
Console.WriteLine( "The constants are as follow :-" );
for ( int i = 0; i < obj.Length; i++)
Console.Write( "{0} " , obj[i]);
}
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
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...