How to convert a string to an enum in C#?
Hello, colleagues! I'm new to C# and encountered a problem. I have an enum for order statuses:
```csharp
public enum OrderStatus
{
Pending,
Processing,
Shipped,
Delivered,
Cancelled
}
```
I receive the status from the user as a string, for example, from a text field or from a JSON response from an API. The string can be like: "Pending", "Shipped" or "Cancelled". I need to convert this string to the corresponding enum value to use it in the program logic.
I tried simply assigning the string to a variable of type `OrderStatus`, but the compiler gives an error. I tried using `Convert.ChangeType()`, but that didn't work either. The only way I found is to write a huge `switch` with many `case`:
```csharp
Order
No answers yet.
Log in to leave an answer
Blogs
How to Write a REST API in Swift in 30 Minutes