0
0
C Sharp (C#)programming~5 mins

Enum parsing from strings in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Enums let us name groups of related values. Parsing from strings helps convert text into these named values so the program understands them.

When reading user input that names an option, like 'Red' or 'Blue'.
When loading settings from a file that stores enum names as text.
When receiving enum values as strings from a web API or database.
When converting command line arguments into enum values.
When you want to safely convert text to enum without errors.
Syntax
C Sharp (C#)
EnumType variable = (EnumType) Enum.Parse(typeof(EnumType), stringValue);

// Or safer:
bool success = Enum.TryParse(stringValue, out EnumType variable);

Enum.Parse throws an error if the string is not a valid enum name.

Enum.TryParse returns true or false to show success, avoiding errors.

Examples
This converts the string "Green" to the enum value Color.Green.
C Sharp (C#)
enum Color { Red, Green, Blue }

Color c = (Color) Enum.Parse(typeof(Color), "Green");
This safely tries to parse "Blue". If it works, c holds Color.Blue.
C Sharp (C#)
enum Color { Red, Green, Blue }

if (Enum.TryParse("Blue", out Color c)) {
    // c is Color.Blue
}
The third argument true makes parsing ignore case, so "red" works for Color.Red.
C Sharp (C#)
enum Color { Red, Green, Blue }

// Case insensitive parsing
Color c = (Color) Enum.Parse(typeof(Color), "red", true);
Sample Program

This program shows how to parse strings to enum values using both Enum.Parse and Enum.TryParse. It also shows how TryParse handles invalid strings safely.

C Sharp (C#)
using System;

class Program {
    enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }

    static void Main() {
        string input = "Friday";

        // Using Enum.Parse
        Day day1 = (Day) Enum.Parse(typeof(Day), input);
        Console.WriteLine($"Parsed with Enum.Parse: {day1}");

        // Using Enum.TryParse
        if (Enum.TryParse("sunday", true, out Day day2)) {
            Console.WriteLine($"Parsed with Enum.TryParse (case insensitive): {day2}");
        } else {
            Console.WriteLine("Failed to parse day.");
        }

        // Try parsing invalid string
        if (Enum.TryParse("Funday", out Day day3)) {
            Console.WriteLine($"Parsed: {day3}");
        } else {
            Console.WriteLine("'Funday' is not a valid Day enum value.");
        }
    }
}
OutputSuccess
Important Notes

Enum.Parse throws an exception if the string is invalid, so use TryParse to avoid crashes.

TryParse has an overload to ignore case, which is helpful for user input.

Always check the result of TryParse before using the parsed enum value.

Summary

Enums group related named values for easy use.

Enum.Parse converts strings to enum but can throw errors if invalid.

Enum.TryParse safely tries to convert strings and tells if it worked.