Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
