C#
Enum.Parse
Learn to convert text to enum with Enum.Parse and IsDefined.
String to enum with Enum.Parse
To convert a string into an enum value, use the Enum.Parse method. The first argument is the type via typeof(EnumName), the second is the string value. If the string does not match a member name, it throws FormatException.
For example, Color c = (Color)Enum.Parse(typeof(Color), "Green"); assigns Color.Green to c. The match is case-sensitive; writing "green" in lowercase throws. That is why a safer method is preferred for user input.
Safe parsing with Enum.TryParse
The Enum.TryParse method does safe parsing like int.TryParse. Instead of throwing, it returns a bool and gives the result through an out parameter. It is ideal for user input.
For example, if (Enum.TryParse<Color>(input, out Color c)) sets c and returns true when input is valid. If not, it returns false and the program continues without crashing. Because it is a generic method, you specify the type with <Color>.
Validity with Enum.IsDefined
To check whether a value (number or string) has a matching enum member, use Enum.IsDefined(typeof(EnumName), value). It works for both numeric and string values and returns a bool.
For example, Enum.IsDefined(typeof(Color), "Green") returns true, while Enum.IsDefined(typeof(Color), 99) returns false. This lets you verify a value is valid before converting and catch errors early.
Exercise Parse the string to enum
Convert input into c using Enum.TryParse<Color>. If parsing succeeds, print c with Console.WriteLine. Use an if on the return value of TryParse. The Color enum is declared at the top of the file.
Show example solution
Declare Color c; then check with if (Enum.TryParse<Color>(input, out c)) and print c with WriteLine.
Example solution:
using System;
enum Color { Red, Green, Blue }
class Program
{
static void Main()
{
string input = "Blue";
Color c;
if (Enum.TryParse<Color>(input, out c))
{
Console.WriteLine(c);
}
}
}
Test yourself
-
What does Parse do with "red" (lowercase)?
Color c = (Color)Enum.Parse(typeof(Color), "red");
- Throws FormatException
- Parses as Red
- Returns null
- Returns the default value
Show answer
Throws FormatException — Correct! Enum.Parse is case-sensitive; 'red' triggers an error.
-
TryParse call
Color c;
bool ok = ____;
Console.WriteLine(ok);
Show answer
Color c;
bool ok = Enum.TryParse<Color>("Red", out c);
Console.WriteLine(ok);
-
Why use Enum.IsDefined?
- Because it is faster
- To prevent invalid values
- Only for strings
- To reset the enum
Show answer
To prevent invalid values — Correct! IsDefined catches invalid values before the conversion.
Next lesson: Flags attribute