Enum.GetUnderlyingType() या Type.GetEnumUnderlyingType() मेथड एन्यूमरेशन के अंतर्निहित पूर्णांक प्रकार (डिफ़ॉल्ट रूप से int, लेकिन byte, short, long, आदि हो सकता है) लौटाता है।
उदाहरण 1: वैध एनम
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));
Type type2 = type.GetEnumUnderlyingType();
Console.Write("Enum Underlying type = " + type2);
Console.WriteLine("\nListing 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 Enum Underlying type = System.Int32 Listing constants .. Car Bus Bike Airplane
उदाहरण 2: गैर-एनम प्रकार (int)
using System;
public class Demo
{
enum Vehicle { Car, Bus, Bike, Airplane }
public static void Main()
{
try
{
Type type = typeof(int);
string[] str = type.GetEnumNames();
Console.WriteLine("GetEnumNames() to return the constant names = " + string.Join(", ", str));
Type type2 = type.GetEnumUnderlyingType();
Console.Write("Enum Underlying type = " + type2);
Console.WriteLine("\nListing 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
GetEnumUnderlyingType केवल एनम प्रकारों पर काम करता है; अन्यथा ArgumentException फेंकता है। अंतर्निहित प्रकार एनम घोषणा में निर्दिष्ट होता है: enum MyEnum : long { ... }। डिफ़ॉल्ट int है। Enum.GetValues और Enum.GetNames संबंधित मेथड्स हैं।