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

Init-only setters in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Init-only setters
O(n)
Understanding Time Complexity

Let's explore how the time it takes to set properties using init-only setters changes as we create more objects.

We want to know how the cost grows when initializing many objects with these setters.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

public record Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

var people = new List();
for (int i = 0; i < n; i++)
{
    people.Add(new Person { Name = $"Person{i}", Age = i });
}

This code creates a list of Person objects, each initialized with a name and age using init-only setters.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating and initializing a Person object inside a loop.
  • How many times: The loop runs n times, once for each Person created.
How Execution Grows With Input

Each new object requires a fixed amount of work to set its properties.

Input Size (n)Approx. Operations
10About 10 object creations and initializations
100About 100 object creations and initializations
1000About 1000 object creations and initializations

Pattern observation: The work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to initialize all objects grows linearly as you create more objects.

Common Mistake

[X] Wrong: "Init-only setters make object creation instant regardless of how many objects."

[OK] Correct: Each object still needs its properties set one by one, so more objects mean more work.

Interview Connect

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

Self-Check

"What if we replaced the init-only setters with regular setters and modified properties after creation? How would the time complexity change?"