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

Expression-bodied methods in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Expression-bodied methods
O(n)
Understanding Time Complexity

We want to understand how fast or slow expression-bodied methods run as the input size changes.

Specifically, we ask: how does the work grow when the method is called with bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

public int Square(int x) => x * x;

public int SumArray(int[] numbers) => numbers.Sum();

public int MultiplyAll(int[] numbers) => numbers.Aggregate(1, (acc, val) => acc * val);

This code shows simple expression-bodied methods: one calculates a square, another sums an array, and the last multiplies all array elements.

Identify Repeating Operations

Look for loops or repeated steps inside these methods.

  • Primary operation: For Square, just one multiplication. For SumArray and MultiplyAll, looping through the array.
  • How many times: The array methods repeat once for each element in the input array.
How Execution Grows With Input

As the array gets bigger, the time to sum or multiply grows too.

Input Size (n)Approx. Operations
10About 10 steps for sum or multiply
100About 100 steps
1000About 1000 steps

Pattern observation: The work grows directly with the number of items in the array.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Expression-bodied methods always run faster because they use less code."

[OK] Correct: The syntax is shorter but the work done depends on what the method does, not how it is written.

Interview Connect

Understanding how expression-bodied methods perform helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

"What if we changed the array methods to use recursion instead of built-in functions? How would the time complexity change?"