C#

Search for a string in Enum and return the Enum

25 September 2026 · 6 min read

Search for a string in Enum and return the Enum

In the world of software development, particularly with languages like C, working with enumerations (enums) is a common practice for defining a set of named integral constants. Enums enhance code readability and maintainability by replacing magic numbers with meaningful names. However, developers often face the challenge of needing to search for a string in Enum and return the Enum member. This task typically arises when processing user input, deserializing data from a database, or integrating with external systems where enum values are represented as strings. Understanding how to accurately and efficiently convert these string representations back into their corresponding enum types is crucial for robust application design.

This article delves into the various techniques available to achieve this conversion, from standard library methods to more advanced approaches involving reflection and custom attributes. We will explore the nuances of each method, discussing their strengths, weaknesses, and optimal use cases. By the end, you’ll have a comprehensive understanding of how to reliably transform strings into enums, ensuring your applications handle data conversions gracefully and performantly.

Why String to Enum Conversion is Essential

The necessity to convert a string representation into its corresponding enum type stems from several practical scenarios in application development. Imagine a user interface where a dropdown menu displays human-readable names like “Pending,” “Approved,” or “Rejected.” Behind the scenes, these might correspond to an OrderStatus enum. When the user selects an option, the application receives a string, which then needs to be converted back to the enum to perform business logic or persist the state correctly.

Another common use case is data serialization and deserialization. When data is stored in databases, configuration files, or transmitted over network protocols (like JSON or XML), enum values are frequently serialized as strings. Upon retrieval, these strings must be accurately mapped back to their enum counterparts to restore the application’s state. Failing to implement a reliable string to enum conversion can lead to runtime errors, inconsistent data, and a poor user experience. This conversion process ensures type safety and allows developers to leverage the strong typing benefits of enums throughout their codebase, rather than relying on error-prone string comparisons.

Furthermore, integrating with third-party APIs often involves receiving data where enumerations are represented as strings. A robust conversion mechanism allows your application to seamlessly interpret this external data and integrate it with your internal enum definitions. This promotes interoperability and reduces the complexity of managing disparate data formats. Without effective strategies to search for a string in Enum and return the Enum, developers would be forced to use less elegant and more error-prone solutions, such as long chains of if-else statements or dictionary lookups, which undermine the benefits of using enums in the first place.

*Infographic: Common String-to-Enum Conversion Scenarios*

A visual representation showing user input, database interaction, and API integration leading to string-to-enum conversion.

Standard Approaches: Enum.Parse and Enum.TryParse -------------------------------------------------

For most straightforward string-to-enum conversions, the .NET framework provides two primary methods: Enum.Parse and Enum.TryParse. These methods are part of the System.Enum class and are designed to handle conversions where the string directly matches an enum member’s name.

Enum.Parse is a synchronous method that attempts to convert the string representation of an enum member to its corresponding enum type. It takes two primary arguments: the type of the enum and the string value. An optional third argument specifies whether the parsing should be case-insensitive. If the string does not match any enum member, or if it’s not a valid enum type, Enum.Parse throws an ArgumentException or an OverflowException, respectively. This makes it suitable for scenarios where you are confident the string will always be valid, or where an exception is the desired error-handling mechanism.

To search for a string in Enum and return the Enum efficiently and without exceptions in C, the recommended approach is to use Enum.TryParse. This method attempts to convert the string representation of an enum name to its corresponding enum type. It returns a boolean value indicating whether the parsing was successful, and if so, it assigns the converted enum value to an out parameter. This non-throwing behavior makes Enum.TryParse ideal for robust error handling, especially when dealing with user input or external data that might contain invalid enum strings. It supports both case-sensitive and case-insensitive parsing, offering flexibility in how string comparisons are performed.

  1. Define your Enum: First, ensure you have an enum defined in your code.
  2. Prepare the String: Get the string you want to convert. This could be from user input, a database, or an API response.
  3. Use Enum.TryParse: Call the static method, passing the enum type, the string, and an out parameter for the result.
  4. Handle the Result: Check the boolean return value. If true, the conversion was successful; otherwise, handle the error.
  5. Example: ``` public enum DayOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } // … inside a method … string dayString = “Tuesday”; DayOfWeek resultDay; if (Enum.TryParse(dayString, out resultDay)) { Console.WriteLine($“Successfully converted ‘{dayString}’ to {resultDay}”); } else { Console.WriteLine($“Failed to convert ‘{dayString}’ to a DayOfWeek enum.”); } // Case-insensitive example string dayStringLower = “friday”; if (Enum.TryParse(dayStringLower, true, out resultDay)) { // ’true’ for case-insensitive Console.WriteLine($“Successfully converted ‘{dayStringLower}’ to {resultDay}”); } else { Console.WriteLine($“Failed to convert ‘{dayStringLower}’ to a DayOfWeek enum.”); }

For more detailed information on these methods, refer to the official Microsoft documentation for Enum.TryParse.

Advanced Techniques: Using DescriptionAttribute for Custom Strings

Sometimes, the string representation of an enum member doesn’t directly match its name. For instance, you might have an enum member named OrderStatus.InProcess, but its display string for users or external systems might be “Order Being Processed”. In such cases, Enum.Parse and Enum.TryParse won’t work directly because they only match against the enum member’s literal name. This is where custom Question & Answer :

I have an enumeration:

public enum MyColours { Red, Green, Blue, Yellow, Fuchsia, Aqua, Orange } 

and I have a string:

string colour = "Red"; 

I want to be able to return:

MyColours.Red 

from:

public MyColours GetColour(string colour) 

So far i have:

public MyColours GetColours(string colour) { string[] colours = Enum.GetNames(typeof(MyColours)); int[] values = Enum.GetValues(typeof(MyColours)); int i; for(int i = 0; i < colours.Length; i++) { if(colour.Equals(colours[i], StringComparison.Ordinal) break; } int value = values[i]; // I know all the information about the matched enumeration // but how do i convert this information into returning a // MyColour enumeration? } 

As you can see, I’m a bit stuck. Is there anyway to select an enumerator by value. Something like:

MyColour(2) 

would result in

MyColour.Green 

check out System.Enum.Parse:

enum Colors {Red, Green, Blue} // your code: Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");