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

Method overriding with virtual and override in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding with virtual and override
O(1)
Understanding Time Complexity

When we use method overriding with virtual and override in C#, it changes how methods are called at runtime.

We want to understand how this affects the time it takes to run the program as it grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


using System;

class Animal {
    public virtual void Speak() {
        Console.WriteLine("Animal speaks");
    }
}

class Dog : Animal {
    public override void Speak() {
        Console.WriteLine("Dog barks");
    }
}

// Usage
Animal myPet = new Dog();
myPet.Speak();
    

This code shows a base class with a virtual method and a derived class overriding it. The method call is decided at runtime.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single method call using virtual dispatch.
  • How many times: Once per call; no loops or recursion here.
How Execution Grows With Input

Since there is no loop or repeated calls, the time to execute the method call stays the same no matter how many objects or classes exist.

Input Size (n)Approx. Operations
101 method call
1001 method call
10001 method call

Pattern observation: The time does not grow with input size because each call is independent.

Final Time Complexity

Time Complexity: O(1)

This means each method call takes a constant amount of time regardless of program size.

Common Mistake

[X] Wrong: "Overriding methods makes the program slower as the number of classes grows."

[OK] Correct: The method call uses a fixed lookup mechanism that does not slow down with more classes or objects.

Interview Connect

Understanding how virtual and override affect method calls helps you explain object-oriented design and performance clearly in interviews.

Self-Check

"What if the method call was inside a loop running n times? How would the time complexity change?"