Enum parsing from strings in C Sharp (C#) - Time & Space Complexity
When we convert text into an enum value, the program checks the text against possible options.
We want to know how the time it takes changes as the number of enum options grows.
Analyze the time complexity of the following code snippet.
enum Color { Red, Green, Blue, Yellow }
string input = "Green";
if (Enum.TryParse(input, out var color))
{
Console.WriteLine($"Parsed color: {color}");
}
else
{
Console.WriteLine("Invalid color");
}
This code tries to convert a string into a matching enum value.
- Primary operation: Checking the input string against each enum name.
- How many times: Once for each enum option until a match is found or all checked.
As the number of enum options grows, the program checks more names one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 string comparisons |
| 100 | Up to 100 string comparisons |
| 1000 | Up to 1000 string comparisons |
Pattern observation: The work grows directly with the number of enum options.
Time Complexity: O(n)
This means the time to parse grows in a straight line as the number of enum values increases.
[X] Wrong: "Parsing an enum from a string is always instant no matter how many options there are."
[OK] Correct: The program checks each enum name one by one, so more options mean more checks and more time.
Understanding how parsing scales helps you explain efficiency and choose better approaches when enums get large.
"What if we used a dictionary to map strings to enum values instead? How would the time complexity change?"