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

Sealed classes and methods in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Sealed classes and methods
O(n)
Understanding Time Complexity

When we use sealed classes or methods, we stop further changes through inheritance. This affects how the program runs when it calls these methods.

We want to see how sealing changes the number of steps the program takes as it runs.

Scenario Under Consideration

Analyze the time complexity of calling a sealed method versus a virtual method.


public class BaseClass
{
    public virtual void VirtualMethod() { /* some work */ }
    public sealed void SealedMethod() { /* some work */ }
}

public class DerivedClass : BaseClass
{
    public override void VirtualMethod() { /* some work */ }
    // Cannot override SealedMethod
}

// Usage
BaseClass obj = new DerivedClass();
obj.VirtualMethod();
obj.SealedMethod();
    

This code shows a base class with a virtual method and a sealed method, and a derived class overriding the virtual method but not the sealed one.

Identify Repeating Operations

Look at what happens when methods are called many times.

  • Primary operation: Calling methods on objects.
  • How many times: Each method call happens once per call, but many calls can happen in a loop or program.
How Execution Grows With Input

Calling a sealed method runs the exact code without extra checks. Calling a virtual method requires checking which version to run.

Input Size (n)Approx. Operations
1010 method calls, each with small overhead
100100 method calls, overhead adds up for virtual calls
10001000 method calls, virtual calls have more overhead than sealed

Pattern observation: Sealed methods avoid extra checks, so their call cost stays simpler as calls grow.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows directly with the number of method calls, but sealed methods have less overhead per call.

Common Mistake

[X] Wrong: "Sealing a method changes how many times it runs or makes it faster in a way that changes overall time complexity."

[OK] Correct: Sealing only removes the option to override and avoids some checks, but the number of calls still grows with input size the same way.

Interview Connect

Understanding how sealed methods affect execution helps you explain performance choices clearly. It shows you know how code structure impacts running time.

Self-Check

"What if the sealed method was changed to virtual and overridden many times? How would the time complexity or overhead change?"