Init-only setters in C Sharp (C#) - Time & Space 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.
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 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.
Each new object requires a fixed amount of work to set its properties.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations and initializations |
| 100 | About 100 object creations and initializations |
| 1000 | About 1000 object creations and initializations |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to initialize all objects grows linearly as you create more objects.
[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.
Understanding how object initialization scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if we replaced the init-only setters with regular setters and modified properties after creation? How would the time complexity change?"