Get the names of the members of the current enumeration type in C#

CsharpServer Side ProgrammingProgramming

<p>To get the names of the members of the current enumeration type, the code is as follows &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/HN915NtK" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">using System; public class Demo { &nbsp; &nbsp;enum Vehicle {Car, Bus, Bike} &nbsp; &nbsp;public static void Main() { &nbsp; &nbsp; &nbsp; try { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Type type = typeof(string); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string[] str = type.GetEnumNames(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;GetEnumName() to return the constant name = &quot; + str); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;Listing constants ..&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0; i &lt; str.Length; i++) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.Write(&quot;{0} &quot;, str[i]); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; catch (ArgumentException e) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;Not an enum!&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.Write(&quot;{0}&quot;, e.GetType(), e.Message); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">Not an enum! System.ArgumentException</pre><h2>Example</h2><p>Let us see another example &minus;</p><p><a class="demo" href="http://tpcg.io/gHZw3LKS" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">using System; public class Demo { &nbsp; &nbsp;enum Vehicle {Car, Bus, Bike, airplane} &nbsp; &nbsp;public static void Main() { &nbsp; &nbsp; &nbsp; try { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Vehicle v = Vehicle.Bike; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Type type = v.GetType(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string[] str = type.GetEnumNames(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;GetEnumName() to return the constant name = &quot; + str); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;Listing constants ..&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0; i &lt; str.Length; i++) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.Write(&quot;{0} &quot;, str[i]); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; catch (ArgumentException e) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(&quot;Not an enum!&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.Write(&quot;{0}&quot;, e.GetType(), e.Message); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">GetEnumName() to return the constant name = System.String[] Listing constants .. Car Bus Bike airplane</pre>
raja
Updated on 06-Dec-2019 12:33:51

Advertisements