---
title: "Convert a string to an enum in C#"  
description: "Convert a string to an enum in C#"  
author: "Utpal Vishwas"  
published: 2023-08-21  
updated: 2023-08-23  
canonical: https://www.mindstick.com/forum/159625/convert-a-string-to-an-enum-in-c-sharp  
category: "c#"  
tags: ["c#", "string", "enum"]  
reading_time: 2 minutes  

---

# Convert a string to an enum in C#

[Convert](https://www.mindstick.com/forum/2093/configurationmanager-appsettings-convert-n-to-n-why) a [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) to an [enum in C#](https://www.mindstick.com/forum/33625/how-to-use-enum-in-c-sharp-dot-net)

## Replies

### Reply by Aryan Kumar

Sure, here are two ways to convert a string to an [enum](https://www.mindstick.com/forum/159626/how-can-i-cast-a-string-to-an-enum) in C#:

1. Using the `Enum.Parse()` method:

C#

```plaintext
enum MyEnum {
  Value1,
  Value2,
  Value3
}

string myString = "Value1";

// Convert the string to an enum using the Enum.Parse() method.
MyEnum myEnum = Enum.Parse(typeof(MyEnum), myString);
```

In this example, the `myString` variable is a string that has the value of `"Value1"`. The `MyEnum` enum has three values: `Value1`, `Value2`, and `Value3`. The `Enum.Parse(typeof(MyEnum), myString)` method casts the `myString` variable to an enum.

1. Using the `try-catch` block:

C#

```plaintext
enum MyEnum {
  Value1,
  Value2,
  Value3
}

string myString = "Value1";

// Convert the string to an enum using the try-catch block.
try {
  myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);
} catch (Exception e) {
  // The string is not a valid enum value.
}
```

In this example, the `myString` variable is a string that has the value of `"Value1"`. The `MyEnum` enum has three values: `Value1`, `Value2`, and `Value3`. The `try-catch` block first tries to cast the `myString` variable to an enum. If the `myString` variable is not a valid enum value, then the `Exception` exception is caught.

Which method you use depends on your specific needs. If you need to cast a string to an enum and you don't need to do any further processing on the enum value, then the `Enum.Parse()` method is a good option. If you need to do further processing on the enum value, then the `try-catch` block is a good option.


---

Original Source: https://www.mindstick.com/forum/159625/convert-a-string-to-an-enum-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
