C# programming
coding tutorial
string conversion
enum in C#
data type conversion

Convert a string to an enum in C#

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In C#, enumerations (enums) are a convenient way to group related named constants. There might be scenarios where you need to convert a string into one of these enums. For example, you may be parsing user input or reading from a file or a database where the values are stored as strings but you want to use the strong typing and clarity of enums within your code.

Understanding Enums in C#

Before diving into converting strings to enums, let's briefly define what an enum is. Enums are a type in C# that consists of a set of named constants called the enumerator list. Usually, they are used to represent a collection of related constants and make your code easier to read and maintain.

Here is a simple example of an enum in C#:

csharp
1enum DayOfWeek
2{
3    Sunday,
4    Monday,
5    Tuesday,
6    Wednesday,
7    Thursday,
8    Friday,
9    Saturday
10}

Converting String to Enum

To convert a string to an enum in C#, you can use the built-in method Enum.Parse or the safer Enum.TryParse method. Below, both methods are explored with examples.

Using Enum.Parse

Enum.Parse converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. This method throws an exception if the conversion is not successful.

Example:

csharp
string day = "Sunday";
DayOfWeek dayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);

Using Enum.TryParse

Enum.TryParse is similar to Enum.Parse but doesn't throw an exception if the conversion fails. Instead, it returns a Boolean value indicating whether the conversion succeeded or failed, which makes it safer to use than Enum.Parse.

Example:

csharp
1string day = "Sunday";
2DayOfWeek dayOfWeek;
3
4if (Enum.TryParse(day, out dayOfWeek))
5{
6    Console.WriteLine($"Successfully parsed: {dayOfWeek}");
7}
8else
9{
10    Console.WriteLine("Failed to parse.");
11}

Handling Case Sensitivity

Both Enum.Parse and Enum.TryParse include an overload that allows you to specify whether the operation should be case-sensitive. By default, the parsing is case-sensitive. However, you can set the ignoreCase parameter to true to handle cases where the case of the input string might not be consistent.

Example using ignoreCase:

csharp
1string day = "sunday";
2DayOfWeek dayOfWeek;
3
4if (Enum.TryParse(day, true, out dayOfWeek))
5{
6    Console.WriteLine($"Successfully parsed: {dayOfWeek}");
7}
8else
9{
10    Console.WriteLine("Failed to parse.");
11}

Best Practices and Error Handling

While converting strings to enums, it's vital to consider the implications of the input data not being valid. If you are using Enum.Parse, always use it inside a try-catch block to handle exceptions gracefully. With Enum.TryParse, always check the returned Boolean value before using the parsed enum value.

Performance Considerations

While using these parsing methods, remember that reflection is used internally, which can be slower than other operations. For critical performance applications, consider other methods of mapping strings to enums, such as using a dictionary if the conversion happens frequently.

Summary Table

Here's a quick summary of the key concepts and functions used for converting a string to an enum:

FunctionCase SensitiveException ThrowReturn Type
Enum.ParseOptionalYesEnum
Enum.TryParseOptionalNoBoolean

Conclusion

Converting a string to an enum in C# is straightforward using either Enum.Parse or Enum.TryParse. The choice between these depends on your specific needs regarding error handling and whether you prefer handling exceptions or a Boolean check. These methods allow the programmer to maintain strong typing and leverage the advantages of enums, offering clear, readable code that efficiently defines groups of related constants.


Course illustration
Course illustration

All Rights Reserved.