Base class and derived class in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using base and derived classes, it's important to see how the program runs as the number of objects grows.
We want to know how the time to run changes when we create and use many objects from these classes.
Analyze the time complexity of the following code snippet.
class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal {
public override void Speak() {
Console.WriteLine("Dog barks");
}
}
void MakeAnimalsSpeak(List<Animal> animals) {
foreach (var animal in animals) {
animal.Speak();
}
}
This code defines a base class and a derived class, then calls a method on each object in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the Speak() method on each animal in the list.
- How many times: Once for each animal in the list, so as many times as the list size.
As the number of animals grows, the number of Speak() calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Speak() |
| 100 | 100 calls to Speak() |
| 1000 | 1000 calls to Speak() |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more animals.
[X] Wrong: "Because of inheritance, calling methods on derived classes is slower and adds extra loops."
[OK] Correct: Calling overridden methods still happens once per object, just like calling any method. Inheritance does not add hidden loops.
Understanding how method calls scale with object count helps you explain performance clearly and confidently in interviews.
"What if we added a nested loop inside the Speak() method? How would the time complexity change?"
Practice
base class in C#?Solution
Step 1: Understand the role of base class
A base class contains common code that multiple classes can share to avoid repetition.Step 2: Compare options with this role
To hold common code that other classes can reuse matches this purpose exactly, while others describe incorrect or unrelated uses.Final Answer:
To hold common code that other classes can reuse -> Option AQuick Check:
Base class = shared code [OK]
- Thinking base class cannot be instantiated
- Confusing base class with interface
- Believing base class only stores data
Car that inherits from a base class Vehicle in C#?Solution
Step 1: Recall C# inheritance syntax
In C#, a derived class uses a colon (:) followed by the base class name.Step 2: Match options with correct syntax
class Car : Vehicle { } uses the correct syntax:class Car : Vehicle { }. Others use incorrect keywords or symbols.Final Answer:
class Car : Vehicle { } -> Option BQuick Check:
Inheritance syntax = colon (:) [OK]
- Using 'inherits' instead of ':'
- Using 'extends' like in Java
- Using arrow '->' symbol
class Animal {
public void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal {
public void Speak() {
Console.WriteLine("Dog barks");
}
}
class Program {
static void Main() {
Animal a = new Dog();
a.Speak();
}
}Solution
Step 1: Understand method hiding vs overriding
TheSpeakmethod inDoghides the base method but is not markedvirtualoroverride.Step 2: Check method call behavior
Sinceais of typeAnimal, it callsAnimal.Speak()ignoringDog's method.Final Answer:
Animal speaks -> Option CQuick Check:
Non-virtual method call = base method [OK]
- Assuming derived method runs without override
- Confusing method hiding with overriding
- Expecting polymorphism without virtual keyword
class Person {
public string Name;
}
class Student : Person {
public string Name;
}
class Program {
static void Main() {
Student s = new Student();
s.Name = "Alice";
Console.WriteLine(s.Name);
}
}Solution
Step 1: Analyze the code execution
The code declares a public fieldNamein bothPersonandStudent, causing the derived field to hide the base one. This is allowed in C#.Step 2: Determine if there is an error
The code compiles (with a compiler warning about hiding), executes successfully, and prints 'Alice' as it accesses the derived class'sNamefield.Final Answer:
No error, code runs and prints 'Alice' -> Option AQuick Check:
Field hiding allowed, no hard error [OK]
- Thinking derived class cannot declare same field name
- Believing missing constructor causes issue
- Mistaking fields for methods that need override
Shape with a method Area() that derived classes Circle and Rectangle must implement differently. Which approach is best in C#?Solution
Step 1: Understand requirement for method implementation in derived classes
The base classShapeshould force derived classes to provide their ownArea()implementation.Step 2: Choose correct C# feature
DeclaringArea()as abstract inShaperequires derived classes to implement it, matching the requirement.Final Answer:
Declare Area() as an abstract method in Shape and implement in derived classes -> Option DQuick Check:
Abstract method = must implement in derived [OK]
- Using virtual without override
- Not declaring method in base class
- Confusing interface with abstract class
