Computer >> Computer tutorials >  >> Programming >> C#

C# Enum Parse Method


The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.

The following is our enumeration.

enum Vehicle { Car, Bus, Truck, Motobike };

Now, use the GetNames() method in a loop to get the enum values. Parse them using the Enum.Parse() method as shown below −

Enum.Parse(typeof(Vehicle)

Example

using System;
public class Demo {
   enum Vehicle { Car, Bus, Truck, Motobike };
   public static void Main() {
      Console.WriteLine("The enumeration...");
      foreach (string v in Enum.GetNames(typeof(Vehicle))) {
         Console.WriteLine("{0} = {1:D}", v, Enum.Parse(typeof(Vehicle), v));
      }
      Console.WriteLine();
   }
}

Output

The enumeration...
Car = 0
Bus = 1
Truck = 2
Motobike = 3