How to convert a string to enum in C#? (Enum.Parse, TryParse, case-insensitive)
Hi everyone! I'm new to C# and stuck on what seems like a simple task.
I have an enum for order statuses:
```csharp
public enum OrderStatus
{
Pending,
Processing,
Shipped,
Delivered,
Cancelled
}
```
The user enters a status in a text field (e.g., "Shipped" or "shipped"). I need to convert this string to an `OrderStatus` value to use it in the program logic.
I tried simply assigning the string to a variable of type `OrderStatus`:
```csharp
string userInput = "Shipped";
OrderStatus status = userInput; // Compilation error: Cannot implicitly convert type 'string' to 'OrderStatus'
```
Naturally, this doesn't work. I know there's an `Enum.Parse` method, but I've read that it throws an exception if the string is not in the enum.
No answers yet.
Log in to leave an answer
Blogs