Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Enum parsing from strings in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Enum parsing from strings
Start with string input
↓
Call Enum.Parse method
↓
Check if string matches enum name
↓
Return enum
↓
Use enum value
The program takes a string, tries to convert it to an enum value using Enum.Parse, and either returns the enum or handles errors if the string doesn't match.
Execution Sample
C Sharp (C#)
enum Color { Red, Green, Blue }
string input = "Green";
Color c = (Color)Enum.Parse(typeof(Color), input);
Console.WriteLine(c);
This code converts the string "Green" to the enum Color.Green and prints it.
Execution Table
StepActionInput StringEnum TypeParse ResultOutput
1Start with input string"Green"ColorN/AN/A
2Call Enum.Parse"Green"ColorMatches 'Green'Color.Green
3Cast to Color enumN/AColorColor.GreenColor.Green
4Print enum valueN/AColorColor.GreenGreen
5EndN/AN/AN/AProgram ends
💡 Parsing succeeds because input string matches an enum name exactly.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
input"Green""Green""Green""Green"
cuninitializedN/AColor.GreenColor.Green
Key Moments - 2 Insights
What happens if the input string does not match any enum name?
Enum.Parse throws an exception because it cannot find a matching enum value, as shown by the absence of a successful parse in the execution_table.
Why do we cast the result of Enum.Parse to the enum type?
Enum.Parse returns an object, so we cast it to the specific enum type to use it as that enum, as shown in Step 3 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of variable 'c' after Step 3?
AColor.Green
Buninitialized
C"Green"
Dnull
💡 Hint
Check the 'Parse Result' and 'Output' columns in Step 3 of the execution_table.
At which step does the program print the enum value?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' and 'Output' columns in the execution_table for when printing happens.
If the input string was "Yellow" which is not in the enum, what would happen?
AEnum.Parse returns null
BEnum.Parse returns default enum value
CEnum.Parse throws an exception
DProgram prints "Yellow"
💡 Hint
Refer to key_moments about what happens when input string does not match any enum name.
Concept Snapshot
Enum parsing from strings in C#:
- Use Enum.Parse(typeof(EnumType), string) to convert string to enum.
- Cast the result to the enum type.
- Throws exception if string doesn't match any enum name.
- Useful to convert user input or text to enum values.
Full Transcript
This example shows how to convert a string like "Green" into an enum value Color.Green using Enum.Parse in C#. The program starts with the input string, calls Enum.Parse with the enum type and string, checks if the string matches an enum name, then casts the result to the enum type. If successful, it prints the enum value. If the string does not match, an exception is thrown. Variables are tracked step-by-step to show how the enum variable 'c' gets assigned. Key moments clarify why casting is needed and what happens on invalid input. The visual quiz tests understanding of variable values at each step and error handling.

Practice

(1/5)
1. What does Enum.Parse do in C#?
easy
A. Checks if a string is a valid enum name without converting
B. Converts an enum value to a string
C. Creates a new enum type at runtime
D. Converts a string to the corresponding enum value

Solution

  1. Step 1: Understand Enum.Parse purpose

    Enum.Parse takes a string and tries to convert it to the matching enum value.
  2. Step 2: Compare options

    Only Converts a string to the corresponding enum value describes converting string to enum value. Others describe different actions.
  3. Final Answer:

    Converts a string to the corresponding enum value -> Option D
  4. Quick Check:

    Enum.Parse converts string to enum [OK]
Hint: Enum.Parse converts string to enum value directly [OK]
Common Mistakes:
  • Thinking Enum.Parse converts enum to string
  • Confusing Enum.Parse with Enum.TryParse
  • Believing Enum.Parse checks validity without conversion
2. Which of the following is the correct syntax to parse a string "Monday" to an enum DayOfWeek using Enum.Parse?
easy
A. DayOfWeek day = Enum.Parse("Monday");
B. DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Monday");
C. DayOfWeek day = Enum.Parse(DayOfWeek, "Monday");
D. DayOfWeek day = Enum.TryParse("Monday", out DayOfWeek day);

Solution

  1. Step 1: Recall Enum.Parse syntax

    The correct syntax requires specifying the enum type with typeof and casting the result.
  2. Step 2: Analyze options

    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Monday"); matches the correct syntax: cast the result of Enum.Parse(typeof(EnumType), string).
  3. Final Answer:

    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Monday"); -> Option B
  4. Quick Check:

    Enum.Parse needs typeof and cast [OK]
Hint: Use typeof(Enum) and cast result for Enum.Parse [OK]
Common Mistakes:
  • Omitting typeof(EnumType)
  • Not casting the result to enum type
  • Confusing Enum.Parse with Enum.TryParse syntax
3. What will be the output of this code?
enum Color { Red, Green, Blue }

string input = "Green";
Color c = (Color)Enum.Parse(typeof(Color), input);
Console.WriteLine(c);
medium
A. Green
B. Runtime error
C. Blue
D. Red

Solution

  1. Step 1: Parse string to enum

    The string "Green" matches the enum member Color.Green, so Enum.Parse returns that value.
  2. Step 2: Print enum value

    Console.WriteLine prints the enum member name, which is "Green".
  3. Final Answer:

    Green -> Option A
  4. Quick Check:

    Enum.Parse("Green") = Color.Green [OK]
Hint: Enum.Parse returns enum matching string name [OK]
Common Mistakes:
  • Expecting numeric value instead of name
  • Assuming case-insensitive parsing by default
  • Thinking it throws error for valid names
4. What is wrong with this code snippet?
enum Status { Active, Inactive }

string input = "Pending";
Status s = (Status)Enum.Parse(typeof(Status), input);
Console.WriteLine(s);
medium
A. It will print "Pending"
B. It will parse to Status.Active by default
C. It will throw a runtime exception
D. It will return null

Solution

  1. Step 1: Check if input matches enum members

    The string "Pending" is not a member of Status enum, so Enum.Parse cannot convert it.
  2. Step 2: Understand Enum.Parse behavior on invalid input

    Enum.Parse throws a runtime exception if the string does not match any enum name.
  3. Final Answer:

    It will throw a runtime exception -> Option C
  4. Quick Check:

    Invalid string causes Enum.Parse exception [OK]
Hint: Enum.Parse throws error if string not in enum [OK]
Common Mistakes:
  • Expecting default enum value on invalid string
  • Thinking it returns null instead of error
  • Confusing with Enum.TryParse behavior
5. You want to safely convert a string "Sunday" to enum DayOfWeek without risking exceptions. Which code snippet correctly does this?
hard
A. bool success = Enum.TryParse("Sunday", true, out DayOfWeek day);
B. DayOfWeek.TryParse("Sunday", out DayOfWeek day);
C. Enum.TryParse(typeof(DayOfWeek), "Sunday", out DayOfWeek day);
D. DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Sunday");

Solution

  1. Step 1: Understand safe parsing with Enum.TryParse

    Enum.TryParse returns a bool indicating success and outputs the parsed enum value.
  2. Step 2: Check correct method signature

    bool success = Enum.TryParse("Sunday", true, out DayOfWeek day); uses Enum.TryParse with ignoreCase=true and out parameter, matching correct safe parsing syntax.
  3. Final Answer:

    bool success = Enum.TryParse("Sunday", true, out DayOfWeek day); -> Option A
  4. Quick Check:

    Enum.TryParse with out and ignoreCase is safe [OK]
Hint: Use Enum.TryParse with out and ignoreCase for safe parse [OK]
Common Mistakes:
  • Using Enum.Parse which throws exceptions
  • Calling TryParse on enum type instead of Enum class
  • Ignoring the out parameter requirement
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard