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

Enum parsing from strings in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enum parsing from strings
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the number of enum options grows, the program checks more names one by one.

Input Size (n)Approx. Operations
10Up to 10 string comparisons
100Up to 100 string comparisons
1000Up to 1000 string comparisons

Pattern observation: The work grows directly with the number of enum options.

Final Time Complexity

Time Complexity: O(n)

This means the time to parse grows in a straight line as the number of enum values increases.

Common Mistake

[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.

Interview Connect

Understanding how parsing scales helps you explain efficiency and choose better approaches when enums get large.

Self-Check

"What if we used a dictionary to map strings to enum values instead? How would the time complexity change?"