C# Enum TryParse() Method


The TryParse() method converts the string representation of one or more enumerated constants to an equivalent enumerated object.

Firstly, set an enum.

enum Vehicle { Bus = 2, Truck = 4, Car = 10 };

Now, let us declare a string array and set some values.

string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };

Now parse the values accordingly using Enum TryParse() method.

Example

 Live Demo

using System;
public class Demo {
   enum Vehicle { Bus = 2, Truck = 4, Car = 10 };
   public static void Main() {
      string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };
      foreach (string val in VehicleList) {
         Vehicle vehicle;
         if (Enum.TryParse(val, true, out vehicle))
         if (Enum.IsDefined(typeof(Vehicle), vehicle) | vehicle.ToString().Contains(","))
         Console.WriteLine("Converted '{0}' to {1}", val, vehicle.ToString());
         else
         Console.WriteLine("{0} is not a value of the enum", val);
         else
         Console.WriteLine("{0} is not a member of the enum", val);
      }
   }
}

Output

Converted '2' to Bus
3 is not a value of the enum
Converted '4' to Truck
Converted 'bus' to Bus
Converted 'Truck' to Truck
Converted 'CAR' to Car

Updated on: 23-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements