TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Enum.Parse, TryParse: Convert String to Enum

Use the Enum.Parse and TryParse methods to convert strings to enums.
Enum.Parse. This converts strings to enum values. It is useful in programs that accept user input as a string, but store the value internally as an enum.
An enum is a more efficient representation than a string. When we have a choice, an enum is better. Enum.TryParse too is covered.Enum
An example. The Enum.Parse method is a static method in the System namespace, so you will need to include System at the top of your file or use the fully qualified name.

Program: Here we see an enum type "PetType" containing a constant "Dog" with value of 2.

Part 1: We call Enum.Parse. The typeof(PetType) returns the enum type. We cast the result of Enum.Parse to the PetType enum type.

Typeof, nameof

Part 2: At the end, we test the result of the Enum.Parse method. We print a short message if the test succeeds.

C# program that parses enums using System; class Program { enum PetType { None, Cat = 1, Dog = 2 } static void Main() { string value = "Dog"; // Part 1: try to convert the string to an enum. PetType pet = (PetType)Enum.Parse(typeof(PetType), value); // Part 2: see if the conversion succeeded. if (pet == PetType.Dog) { Console.WriteLine("Equals dog."); } } } Output Equals dog.
Exceptions. An exception may be raised when parsing enums. When the contents of the string you try to parse is not represented in the enum, you must handle the exception.

Example: Please look at the try-catch block. The code catches all errors, which is sufficient for many small applications.

String: The string in the example isn't found in the enum PetType, so the enum variable is set to PetType.None.

Note: This is the fallback behavior. For important applications, you will log the exception.

TryCatch
C# program that shows enum exceptions using System; class Program { enum PetType { None, Cat = 1, Dog = 2 } static void Main() { // The enum doesn't contain this value. string value = "Bat"; // Try to convert the string to an enum. PetType pet; try { pet = (PetType)Enum.Parse(typeof(PetType), value); } catch (Exception ex) { // The conversion failed. Console.WriteLine("FAILED"); Console.WriteLine(ex.Message); // Set fallback value. pet = PetType.None; } // See if the conversion succeeded. if (pet == PetType.Dog) { } } } Output FAILED Requested value 'Bat' was not found.
Enum.TryParse. Please notice the names of the enumerated constants. Before calling Enum.TryParse, you can declare a variable of the enum type. You do not need to initialize it.

Then: Test the result of Enum.TryParse for true or false. If the method returns true, then the string was successfully parsed.

C# program that uses Enum.TryParse method using System; enum Importance { None, Low, Medium, Critical } class Program { static void Main() { // The input value. string value = "Medium"; // An uninitialized variable. Importance importance; // Call Enum.TryParse method. if (Enum.TryParse(value, out importance)) { // We now have an enum type. Console.WriteLine(importance == Importance.Medium); } } } Output True
A quirk. The Enum.TryParse method will parse a string representation of a number as an enum value. This behavior might not be expected. Consider using the Enum.IsDefined method to test.

Tip: Whenever you have a string that you want to convert into an enum, consider using the Enum.TryParse static method.

TryParse: This method provides a clear and useful calling convention, the tester-doer pattern. It requires the .NET Framework 4.0.

C# program that shows Enum.TryParse quirk using System; enum Importance { None = 0, Low = 1 } class Program { static void Main() { Importance importance; // ... Try to parse the string "1". if (Enum.TryParse("1", out importance)) { // ... "1" is treated as "Low". Console.WriteLine(importance); } } } Output Low
Enum.IsDefined. Please consider calling Enum.TryParse before calling IsDefined. If TryParse returns true, and IsDefined succeeds, you have a correct string value.

Note: Thanks to Thorsten Pontow and Rob for providing information about how to use Enum.IsDefined with Enum.TryParse.

Quote: The example defines a Colors enumeration, calls the TryParse... method to convert strings to their corresponding enumeration values, and calls the IsDefined method.

Enum.TryParse: Microsoft Docs
C# program that uses Enum.IsDefined using System; enum Importance { None = 0, Low = 1 } class Program { static void Main() { // ... "1" is not defined. // ... "Low" is defined. Console.WriteLine(Enum.IsDefined(typeof(Importance), "1")); Console.WriteLine(Enum.IsDefined(typeof(Importance), "Low")); } } Output False True
A summary. Enum.Parse receives the typeof operator result and the string input. We saw a successful call to Enum.Parse—and one that failed and threw an exception.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf