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

Enum parsing from strings in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an enum in C#?
An enum (short for enumeration) is a special data type that lets you define a set of named constants, making code easier to read and maintain.
Click to reveal answer
beginner
How do you parse a string to an enum value in C#?
You use Enum.Parse(typeof(EnumType), stringValue) or Enum.TryParse<EnumType>(stringValue, out var result) to convert a string to an enum value.
Click to reveal answer
intermediate
What is the difference between Enum.Parse and Enum.TryParse?
Enum.Parse throws an exception if parsing fails, while Enum.TryParse returns a boolean indicating success or failure without throwing exceptions.
Click to reveal answer
intermediate
How can you make enum parsing case-insensitive?
Use the overload Enum.TryParse<EnumType>(stringValue, ignoreCase: true, out var result) to ignore case differences when parsing.
Click to reveal answer
intermediate
What happens if you try to parse a string that is not a valid enum name?
Using Enum.Parse will throw a System.ArgumentException. Using Enum.TryParse will return false and set the output to the default enum value.
Click to reveal answer
Which method safely parses a string to an enum without throwing exceptions?
AEnum.Parse
BEnum.TryParse
CEnum.ToString
DEnum.GetName
How do you parse a string to an enum ignoring case differences?
AEnum.Parse without parameters
BEnum.Parse with ignoreCase parameter set to true
CEnum.TryParse with ignoreCase parameter set to true
DEnum.ToString with ignoreCase
What exception does Enum.Parse throw if parsing fails?
ASystem.FormatException
BSystem.NullReferenceException
CSystem.InvalidOperationException
DSystem.ArgumentException
What is the return type of Enum.TryParse?
Abool
Benum type
Cvoid
Dstring
Which of these is a valid way to parse a string to an enum value Color?
AEnum.TryParse<Color>("Red", out var color)
BEnum.Parse<Color>("Red")
CColor.Parse("Red")
DEnum.ToString("Red")
Explain how to convert a string to an enum value in C# and handle invalid input safely.
Think about methods that avoid exceptions and how to check if parsing worked.
You got /5 concepts.
    Describe the difference between Enum.Parse and Enum.TryParse when parsing strings to enums.
    One method throws exceptions on failure, the other returns a success flag.
    You got /4 concepts.