Auto-implemented properties in C Sharp (C#) - Time & Space Complexity
Let's see how the time it takes to use auto-implemented properties changes as we work with more objects.
We want to know how fast the program runs when getting or setting these properties many times.
Analyze the time complexity of the following code snippet.
public class Person
{
public string Name { get; set; }
}
var people = new List();
for (int i = 0; i < n; i++)
{
var p = new Person();
p.Name = "Person " + i;
people.Add(p);
}
This code creates a list of people and sets their names using auto-implemented properties.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that creates and sets the Name property for each Person object.
- How many times: It runs once for each item from 0 up to n-1, so n times.
Each time we add one more person, the program does one more set of property operations.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 sets of Name property assignments |
| 100 | About 100 sets of Name property assignments |
| 1000 | About 1000 sets of Name property assignments |
Pattern observation: The work grows directly with the number of people; double the people, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items you process.
[X] Wrong: "Auto-implemented properties make setting values instant, so time doesn't grow with more items."
[OK] Correct: Even though the property code is simple, setting it still happens once per item, so more items mean more work.
Understanding how simple property access scales helps you explain performance clearly and shows you know how code runs as data grows.
"What if we changed the property to have a custom setter that does extra work? How would the time complexity change?"