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

Property validation logic in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Property validation logic
O(n)
Understanding Time Complexity

When we check if a property value is valid, the time it takes depends on how many checks we do.

We want to know how the time grows when we add more validation rules or data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public class User
{
    private string _email;
    public string Email
    {
        get => _email;
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("Email cannot be empty");
            if (!value.Contains("@"))
                throw new ArgumentException("Email must contain '@'");
            _email = value;
        }
    }
}
    

This code checks two simple rules when setting the Email property: it must not be empty and must contain '@'.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking if the string contains '@' using the Contains method.
  • How many times: This check scans the string characters once each time the property is set.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10 (characters)About 10 checks to find '@'
100 (characters)About 100 checks
1000 (characters)About 1000 checks

Pattern observation: The time to validate grows roughly in direct proportion to the length of the string.

Final Time Complexity

Time Complexity: O(n)

This means the time to validate the property grows linearly with the length of the input string.

Common Mistake

[X] Wrong: "Checking if a string contains a character is always instant, so time doesn't grow with input size."

[OK] Correct: The check looks at each character until it finds '@', so longer strings take more time.

Interview Connect

Understanding how simple validation scales helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if we added multiple validation rules that each scan the string? How would the time complexity change?"