Type.GetEnumNames() मेथड एन्यूमरेशन स्थिरांक के नामों का एक सरणी लौटाता है। यह केवल एनम प्रकारों पर काम करता है; अन्यथा ArgumentException फेंकता है।
उदाहरण 1: गैर-एनम प्रकार (string)
using System;
public class Demo
{
enum Vehicle { Car, Bus, Bike }
public static void Main()
{
try
{
Type type = typeof(string);
string[] str = type.GetEnumNames();
Console.WriteLine("GetEnumNames() to return the constant names = " + string.Join(", ", str));
Console.WriteLine("Listing constants ..");
for (int i = 0; i < str.Length; i++)
Console.Write("{0} ", str[i]);
}
catch (ArgumentException e)
{
Console.WriteLine("Not an enum!");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
आउटपुट
Not an enum! System.ArgumentException
उदाहरण 2: वैध एनम
using System;
public class Demo
{
enum Vehicle { Car, Bus, Bike, Airplane }
public static void Main()
{
try
{
Vehicle v = Vehicle.Bike;
Type type = v.GetType();
string[] str = type.GetEnumNames();
Console.WriteLine("GetEnumNames() to return the constant names = " + string.Join(", ", str));
Console.WriteLine("Listing constants ..");
for (int i = 0; i < str.Length; i++)
Console.Write("{0} ", str[i]);
}
catch (ArgumentException e)
{
Console.WriteLine("Not an enum!");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
आउटपुट
GetEnumNames() to return the constant names = Car, Bus, Bike, Airplane Listing constants .. Car Bus Bike Airplane
GetEnumNames नामों को घोषणा क्रम में लौटाता है (मूल्य क्रम नहीं)। नामों के साथ मूल्यों को प्राप्त करने के लिए Enum.GetValues और Enum.GetName का उपयोग करें। यह रिफ्लेक्शन-आधारित है; प्रदर्शन-महत्वपूर्ण कोड में कैश करें।