Sealed classes and methods in C Sharp (C#) - Time & Space 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.
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.
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.
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 |
|---|---|
| 10 | 10 method calls, each with small overhead |
| 100 | 100 method calls, overhead adds up for virtual calls |
| 1000 | 1000 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.
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.
[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.
Understanding how sealed methods affect execution helps you explain performance choices clearly. It shows you know how code structure impacts running time.
"What if the sealed method was changed to virtual and overridden many times? How would the time complexity or overhead change?"