Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

Popular tracks

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

functionality.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • OOP is a programming paradigm that organizes software around objects, which

contain data (fields/properties) and behavior (methods/functions).

  • Helps model real-world entities and their interactions.
Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Promotes code reusability through classes and objects.
  • Easier to maintain and extend large applications.
  • Models real-world problems better.
  • Supports modularity, abstraction, and encapsulation, which procedural

programming lacks.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

class Vehicle {} // Base

class Car : Vehicle {} // Single/Multilevel

class Bike : Vehicle {} // Hierarchical

Permalink

C# OOP C# Programming Tutorial · OOP

overloading/overriding).

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encourages modular code → easier to maintain and test.
  • Reduces code duplication through inheritance and composition.
  • Improves scalability and flexibility in large projects.
  • Enhances team collaboration as objects represent real-world entities.
Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • A blueprint or template for creating objects.
  • Defines properties (data) and methods (behavior) that the objects will have.

public class Car

public string Model { get; set; }

public void Start() { Console.WriteLine("Car started"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • An instance of a class with actual values.
  • Represents a real-world entity in memory.

Car myCar = new Car(); // Object of Car class

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Class Object

Definition Blueprint/Template Instance of a class

Memory Does not occupy

memory

Occupies memory

Example class Car { } Car myCar = new

Car();

Permalink

C# OOP C# Programming Tutorial · OOP

  • A special method used to initialize objects when they are created.
  • Has the same name as the class and no return type.

public class Car

public string Model;

public Car(string model) { Model = model; }

Car car = new Car("Tesla");

Permalink

C# OOP C# Programming Tutorial · OOP

  • A method called automatically when an object is destroyed.
  • Used to release resources before the object is removed from memory.
  • In C#, destructors are rarely needed due to garbage collection.

~Car() { Console.WriteLine("Car object destroyed"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Instance members → Belong to each object, require object to access.
  • Static members → Belong to the class itself, shared by all objects.

public class Car

public string Model; // Instance

public static int Count; // Static

Permalink

C# OOP C# Programming Tutorial · OOP

  • The practice of hiding internal details of a class and exposing only necessary

functionality through access modifiers and properties.

private int speed;

public int Speed

get { return speed; }

set { speed = value; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Hiding implementation details and showing only the essential features of an

object.

  • Achieved using abstract classes and interfaces.

abstract class Vehicle

public abstract void Start();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Ability of an object to take multiple forms.
  • Types:
  • Compile-time (method overloading)
  • Run-time (method overriding)

Vehicle v = new Car();

v.Start(); // Run-time polymorphism

Permalink

C# OOP C# Programming Tutorial · OOP

  • Car object:
  • Class → Car
  • Objects → myCar, yourCar
  • Properties → Color, Model, Speed
  • Methods → Start(), Stop(), Accelerate()
  • Shows encapsulation, inheritance (e.g., ElectricCar : Car), and polymorphism in

action.

🔹 Section 2: Encapsulation – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encapsulation is the mechanism of hiding internal details of an object and

exposing only necessary functionalities.

  • It helps in protecting data and maintaining control over how it is accessed or

modified.

Example: A BankAccount class hides its balance and only allows deposit/withdraw

operations:

private decimal balance;

public void Deposit(decimal amount) { if(amount > 0) balance +=

amount; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • By making fields private, external code cannot directly modify sensitive data.
  • Access is controlled via methods or properties, enforcing validation rules.

Example: Prevent withdrawing more than the account balance:

public void Withdraw(decimal amount)

if (amount <= balance) balance -= amount;

else throw new InvalidOperationException("Insufficient

balance");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Use private fields to store data.
  • Expose controlled access via public properties or methods.
  • Apply validation logic inside these methods/properties.

private int age;

public int Age

get { return age; }

set { if (value > 0) age = value; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Keywords that define visibility of class members.
  • Common C# modifiers:
  • private → accessible only inside the class
  • public → accessible from anywhere
  • protected → accessible in class and derived classes
  • internal → accessible within the same assembly
  • protected internal → accessible in derived classes or same assembly
Permalink

C# OOP C# Programming Tutorial · OOP

  • Private → Hides data from outside access, ensuring security.
  • Public → Provides controlled access through properties or methods.

Example:

private decimal balance; // hidden

public decimal Balance { get { return balance; } } // read-only

access

Permalink

C# OOP C# Programming Tutorial · OOP

  • Internal → Accessible only within the same assembly.
  • Protected → Accessible in the class and derived classes.
  • Protected Internal → Accessible in derived classes or within the same assembly.

Example:

protected string accountType; // accessible in derived classes

internal string branchCode; // accessible within same assembly

Permalink

C# OOP C# Programming Tutorial · OOP

  • Technically yes, but not recommended.
  • Makes the data vulnerable to invalid modifications.
  • Encapsulation recommends private fields + public properties.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Properties provide controlled access to private fields.
  • Enable validation, read-only/write-only access, and future flexibility.

Example:

private int score;

public int Score

get { return score; }

set { if (value >= 0) score = value; } // validation

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encapsulation → Hides internal data, focuses on data protection.
  • Abstraction → Hides implementation details, focuses on simplifying complex

systems.

Permalink

C# OOP C# Programming Tutorial · OOP

Real-World Example: Bank Account Management

public class BankAccount

private string accountNumber; // private field

private decimal balance; // private field

public string AccountNumber { get { return accountNumber; } } //

read-only

public decimal Balance { get { return balance; } } //

read-only

public BankAccount(string accNum, decimal initialBalance)

accountNumber = accNum;

balance = initialBalance >= 0 ? initialBalance : throw new

ArgumentException("Invalid balance");

public void Deposit(decimal amount)

if(amount > 0) balance += amount;

else throw new ArgumentException("Deposit must be

positive");

public void Withdraw(decimal amount)

if(amount > 0 && amount <= balance) balance -= amount;

else throw new InvalidOperationException("Insufficient

balance");

// Usage

BankAccount myAccount = new BankAccount("ACC123", 1000);

myAccount.Deposit(500); // Balance becomes 1500

myAccount.Withdraw(200); // Balance becomes 1300

Console.WriteLine($"Account: {myAccount.AccountNumber}, Balance:

{myAccount.Balance}");

Explanation:

  • accountNumber and balance are private, protecting sensitive data.
  • Controlled access via methods ensures data integrity.
  • Demonstrates real-world encapsulation in action.

🔹 Section 3: Abstraction – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstraction is the process of hiding the internal implementation details of a

system and exposing only the essential features.

  • It allows developers to focus on what an object does, not how it does it.

Example: A Vehicle class exposes Start() method without revealing engine details.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Simplifies complex systems by exposing only relevant functionality.
  • Enhances maintainability, readability, and reusability of code.
  • Reduces dependency on implementation details, making systems more flexible.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Using abstract classes or interfaces.
  • Abstract classes can have abstract and non-abstract methods.
  • Interfaces define method signatures only.

abstract class Vehicle

public abstract void Start();

interface IDriveable

void Drive();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Classes that cannot be instantiated directly and may contain abstract methods

(without implementation).

  • Can have fields, constructors, and concrete methods.

abstract class Animal

public abstract void MakeSound();

public void Sleep() => Console.WriteLine("Sleeping");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces define a contract of methods, properties, or events that implementing

classes must follow.

  • Interfaces provide full abstraction without any implementation (C# 8+ allows default

methods).

interface IFlyable

void Fly();

Permalink

C# OOP C# Programming Tutorial · OOP

  • By exposing method signatures only, interfaces hide the implementation.
  • Allows multiple classes to implement the interface differently, providing flexibility

and decoupling.

class Bird : IFlyable

public void Fly() => Console.WriteLine("Bird is flying");

class Airplane : IFlyable

public void Fly() => Console.WriteLine("Airplane is flying");

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Abstract Class Interface

Methods Can have abstract +

concrete methods

Only abstract methods (C# 8+ allows default

implementation)

Fields Can have fields Cannot have fields

Inheritance Single inheritance Multiple interfaces can be implemented

Constructo

Can have constructors Cannot have constructors

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, abstract classes cannot be instantiated directly.
  • Must be inherited by a derived class which implements abstract methods.

abstract class Shape { public abstract void Draw(); }

// Shape s = new Shape(); // Not allowed

class Circle : Shape { public override void Draw() =>

Console.WriteLine("Circle"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can have concrete methods with implementation.
  • Allows shared behavior for derived classes.

abstract class Animal

public void Sleep() => Console.WriteLine("Sleeping");

public abstract void MakeSound();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Reduces system complexity by focusing on essential features.
  • Decouples modules, making large systems easier to maintain and extend.
  • Promotes code reuse and flexibility.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Hides implementation details, exposing only what is necessary.
  • Users interact with interfaces or abstract methods, not the full system logic.
  • Simplifies testing, maintenance, and understanding of code.
Permalink

C# OOP C# Programming Tutorial · OOP

Real-World Example: Payment Processing

// Abstract class

abstract class Payment

public abstract void Pay(decimal amount);

public void ShowReceipt(decimal amount) =>

Console.WriteLine($"Paid: {amount:C}");

// Derived classes implement abstraction

class CreditCardPayment : Payment

public override void Pay(decimal amount) =>

Console.WriteLine($"Paid {amount:C} using Credit Card");

class PayPalPayment : Payment

public override void Pay(decimal amount) =>

Console.WriteLine($"Paid {amount:C} using PayPal");

// Usage

Payment payment1 = new CreditCardPayment();

payment1.Pay(500);

payment1.ShowReceipt(500);

Payment payment2 = new PayPalPayment();

payment2.Pay(300);

payment2.ShowReceipt(300);

Explanation:

  • Payment defines what a payment should do (abstract method Pay).
  • Derived classes (CreditCardPayment, PayPalPayment) define how payment is

made.

  • Users interact only with the abstract interface, not the internal logic.

🔹 Section 4: Inheritance – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Inheritance is an OOP mechanism where a class (derived/child) inherits

properties and methods from another class (base/parent).

  • Promotes code reusability and hierarchical relationships.

class Vehicle { public void Start() => Console.WriteLine("Vehicle

started"); }

class Car : Vehicle { } // Car inherits from Vehicle

Permalink

C# OOP C# Programming Tutorial · OOP

  • Base Class (Parent) → Class whose members are inherited.
  • Derived Class (Child) → Class that inherits from base class.

class Vehicle { public void Start() {} } // Base

class Car : Vehicle {} // Derived

Permalink

C# OOP C# Programming Tutorial · OOP

  • Using the colon (:) symbol.
  • Derived class can access public/protected members of the base class.

class Vehicle { public void Start() => Console.WriteLine("Start"); }

class Car : Vehicle { }

Car myCar = new Car();

myCar.Start(); // Inherited method

Permalink

C# OOP C# Programming Tutorial · OOP

  • Calls the constructor of the base class from a derived class.
  • Ensures base class initialization before derived class constructor runs.

class Vehicle { public Vehicle(string brand) {

Console.WriteLine(brand); } }

class Car : Vehicle

public Car(string brand) : base(brand) { Console.WriteLine("Car

created"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, C# does not support multiple class inheritance to avoid ambiguity.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use interfaces to achieve multiple inheritance.
  • A class can implement multiple interfaces.

interface IFlyable { void Fly(); }

interface IDriveable { void Drive(); }

class FlyingCar : IFlyable, IDriveable { public void Fly() {} public

void Drive() {} }

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Inheritance Composition

Relationship "is-a" "has-a"

Reuse Derived class reuses base

class

Object contains other

objects

Flexibility Less flexible More flexible

Example:

  • Inheritance → Car is a Vehicle
  • Composition → Car has a Engine
Permalink

C# OOP C# Programming Tutorial · OOP

  • virtual → Marks a base class method as overridable.
  • override → Overrides a virtual method in the derived class.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Prevents a class from being inherited or a method from being overridden.

sealed class FinalClass { }

class Car : FinalClass { } // Not allowed

Permalink

C# OOP C# Programming Tutorial · OOP

  • override → Overrides a virtual method in base class (runtime polymorphism).
  • new → Hides a base class method (compile-time hiding, not true overriding).

class Vehicle { public void Start() => Console.WriteLine("Vehicle");

class Car : Vehicle { public new void Start() =>

Console.WriteLine("Car"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Common functionality is implemented in base class.
  • Derived classes reuse the code without duplicating it, reducing maintenance effort.
Permalink

C# OOP C# Programming Tutorial · OOP

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Base class constructor executes first, then derived class constructor.
  • Ensures base members are initialized before derived members.
Permalink

C# OOP C# Programming Tutorial · OOP

  • No, private members are hidden from derived classes.
  • Can access protected, internal, or public members.

class Vehicle { private int id; protected string model; }

class Car : Vehicle { /* cannot access id, can access model */ }

🔹 Section 5: Polymorphism – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Polymorphism means “many forms”.
  • It allows objects of different types to be treated as objects of a common base

type.

  • Achieved through method overloading, overriding, and interfaces.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Also called static polymorphism.
  • Resolved at compile time.
  • Achieved through method overloading or operator overloading.

class Calculator

public int Add(int a, int b) => a + b;

public double Add(double a, double b) => a + b; // Overloaded

method

Permalink

C# OOP C# Programming Tutorial · OOP

  • Also called dynamic polymorphism.
  • Resolved at runtime using method overriding.

class Vehicle { public virtual void Start() =>

Console.WriteLine("Vehicle starts"); }

class Car : Vehicle { public override void Start() =>

Console.WriteLine("Car starts"); }

Vehicle v = new Car();

v.Start(); // Calls Car's Start() at runtime

Permalink

C# OOP C# Programming Tutorial · OOP

  • Same method name with different parameters in the same class.
  • Enables compile-time polymorphism.

class MathHelper

public int Multiply(int a, int b) => a * b;

public int Multiply(int a, int b, int c) => a * b * c; //

Overloaded

Permalink

C# OOP C# Programming Tutorial · OOP

  • Derived class provides a new implementation for a virtual method in base class.
  • Enables runtime polymorphism.

class Vehicle { public virtual void Start() =>

Console.WriteLine("Vehicle starts"); }

class Car : Vehicle { public override void Start() =>

Console.WriteLine("Car starts"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, constructors can have multiple signatures in the same class.

class Car

public Car() { }

public Car(string model) { }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, constructors cannot be inherited or overridden.
  • Base class constructor can be called using : base(), but cannot be overridden.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Defining custom behavior for operators (+, -, *, etc.) for a class.

class Point

public int X, Y;

public static Point operator +(Point a, Point b) => new Point {

X = a.X + b.X, Y = a.Y + b.Y };

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Overloading Overriding

Compile/Runtime Compile-time Runtime

Same signature? No, different parameters Same

signature

Virtual required? No Yes

Inheritance

required?

Not required Required

Permalink

C# OOP C# Programming Tutorial · OOP

  • Early binding → Resolved at compile time (e.g., method overloading).
  • Late binding → Resolved at runtime (e.g., method overriding with virtual/override).
Permalink

C# OOP C# Programming Tutorial · OOP

  • object is the base class for all C# types.
  • Enables polymorphism, as any object can be referred using object type.

object obj = new Car();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Through:
Permalink

C# OOP C# Programming Tutorial · OOP

abstract class Shape { public abstract void Draw(); }

class Circle : Shape { public override void Draw() =>

Console.WriteLine("Drawing Circle"); }

class Rectangle : Shape { public override void Draw() =>

Console.WriteLine("Drawing Rectangle"); }

Shape s1 = new Circle();

Shape s2 = new Rectangle();

s1.Draw(); // Circle's Draw

s2.Draw(); // Rectangle's Draw

Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces allow different classes to implement the same contract, enabling

dynamic behavior at runtime.

interface IDriveable { void Drive(); }

class Car : IDriveable { public void Drive() =>

Console.WriteLine("Car drives"); }

class Bike : IDriveable { public void Drive() =>

Console.WriteLine("Bike drives"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Another term for runtime polymorphism, achieved via method overriding.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Code depends on interfaces or base classes, not concrete implementations.
  • Makes system flexible, extendable, and easier to maintain.

void StartVehicle(Vehicle v) { v.Start(); } // Works with any

derived type

Permalink

C# OOP C# Programming Tutorial · OOP

Advantages:

  • Promotes code reuse and flexibility
  • Enables loose coupling
  • Supports extensible architecture

Disadvantages:

  • May introduce runtime overhead
  • Can make code harder to understand if overused
  • Requires careful design to avoid ambiguity

🔹 Section 6: Interfaces in C# – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • An interface is a contract that defines method signatures, properties, events, or

indexers without providing implementation.

  • Classes or structs that implement the interface must provide the implementation.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use the interface keyword.

interface IDriveable

void Drive();

int Speed { get; set; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Use the colon (:) symbol and implement all members.

class Car : IDriveable

public int Speed { get; set; }

public void Drive() => Console.WriteLine("Car is driving");

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, interfaces cannot have fields. Only methods, properties, events, or indexers.
Permalink

C# OOP C# Programming Tutorial · OOP

  • No, interfaces cannot have constructors.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, starting from C# 8, interfaces can contain static methods.

interface IUtility

static void Show() => Console.WriteLine("Static method in

interface");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, methods can have default implementations in interfaces.

interface ILogger

void Log(string message);

void LogWarning(string message) => Console.WriteLine("Warning: "

+ message);

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Interface Class

Implementatio

No implementation (except default

methods)

Can have full

implementation

Fields Cannot have fields Can have fields

Instantiation Cannot instantiate Can instantiate

Inheritance Can inherit multiple interfaces Single class inheritance only

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, a class can implement multiple interfaces, solving multiple inheritance issues.

class FlyingCar : IDriveable, IFlyable

public void Drive() => Console.WriteLine("Driving");

public void Fly() => Console.WriteLine("Flying");

Permalink

C# OOP C# Programming Tutorial · OOP

  • The implementing class must provide a single implementation for both interfaces.
  • Or use explicit interface implementation to differentiate.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, explicit implementation allows a class to implement interface members

separately.

class Car : IDriveable

void IDriveable.Drive() => Console.WriteLine("Explicit drive");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Implementing an interface member explicitly so it can only be called via interface

reference, not class object.

IDriveable car = new Car();

car.Drive(); // Works

// Car c = new Car(); c.Drive(); // Won't compile

Permalink

C# OOP C# Programming Tutorial · OOP

  • Define contracts for classes.
  • Achieve abstraction, polymorphism, and loose coupling.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Expose method signatures without implementation.
  • Users interact with the interface, not the underlying implementation.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Code depends on interface, not concrete class.
  • Makes it easier to swap implementations without changing dependent code.

void StartVehicle(IDriveable vehicle) { vehicle.Drive(); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces allow DI frameworks to inject concrete implementations at runtime.
  • Promotes flexibility and testability.

public class CarService

private readonly IDriveable _vehicle;

public CarService(IDriveable vehicle) { _vehicle = vehicle; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Provides a standard method to compare objects for sorting.

class Employee : IComparable<Employee>

public int Id { get; set; }

public int CompareTo(Employee other) =>

this.Id.CompareTo(other.Id);

Permalink

C# OOP C# Programming Tutorial · OOP

  • Provides Dispose() method for releasing unmanaged resources.

class FileHandler : IDisposable

public void Dispose() => Console.WriteLine("Resources

released");

Permalink

C# OOP C# Programming Tutorial · OOP

  • IEnumerable → Provides collection traversal capability (GetEnumerator()

method).

  • IEnumerator → Used to iterate over a collection (MoveNext(), Current,

Reset()).

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, interfaces can inherit from other interfaces, forming a hierarchy.

interface IFlyable { void Fly(); }

interface IAdvancedFlyable : IFlyable { void Loop(); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces with no methods or properties, used to mark classes for special

behavior.

  • Example: ISerializable marks classes as serializable.

🔹 Section 7: Abstract Classes in C# – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • An abstract class is a class that cannot be instantiated directly.
  • Can contain abstract methods (without implementation) and concrete methods

(with implementation).

  • Used to define a common base for other classes.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use the abstract keyword.

abstract class Vehicle

public abstract void Start();

public void Stop() => Console.WriteLine("Vehicle stopped");

Permalink

C# OOP C# Programming Tutorial · OOP

  • A method declared with abstract without implementation.
  • Must be overridden in a derived class.

abstract class Vehicle

public abstract void Start();

class Car : Vehicle

public override void Start() => Console.WriteLine("Car

started");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can have fields, properties, and constants.

abstract class Vehicle

protected string Brand;

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, constructors are used to initialize fields in derived classes.

abstract class Vehicle

protected string Brand;

public Vehicle(string brand) { Brand = brand; }

class Car : Vehicle

public Car(string brand) : base(brand) { }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can implement interfaces partially or fully.
  • Derived classes must implement any remaining abstract members.

interface IDriveable { void Drive(); }

abstract class Vehicle : IDriveable { public abstract void Drive();

class Car : Vehicle { public override void Drive() =>

Console.WriteLine("Car drives"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, abstract classes cannot be sealed.
  • A sealed class cannot be inherited, while abstract classes are meant to be

inherited.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can have private members, but derived classes cannot

access them.

  • Private members can be accessed via protected or public methods.
Permalink

C# OOP C# Programming Tutorial · OOP

  • No, a class cannot be both abstract and static.
  • Abstract classes are for inheritance, static classes cannot be inherited.
Permalink

C# OOP C# Programming Tutorial · OOP

Feature Abstract Method Virtual Method

Implementatio

No implementation Has implementation

Must override? Must be overridden Optional to override

Class type Must be in abstract class Can be in any class

Purpose Force derived classes to

implement

Allow derived class to optionally

override

Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstract classes can provide shared implementation, fields, and constructors.
  • Useful when multiple classes share common behavior along with enforced

abstraction.

Permalink

C# OOP C# Programming Tutorial · OOP

abstract class Employee

public string Name { get; set; }

public abstract void Work();

public void Report() => Console.WriteLine("Reporting work

done");

class Developer : Employee

public override void Work() => Console.WriteLine("Writing

code");

class Tester : Employee

public override void Work() => Console.WriteLine("Testing

application");

// Usage

Employee dev = new Developer() { Name = "Alice" };

dev.Work();

dev.Report();

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Abstract Class Normal Class

Instantiation Cannot instantiate Can instantiate

Methods Can have abstract methods All methods must have implementation

Purpose Serve as base for

inheritance

General purpose use

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, abstract methods must be overridden with override in derived classes.
  • You can then mark the overriding method as virtual to allow further overriding in

subclasses.

abstract class Vehicle { public abstract void Start(); }

class Car : Vehicle { public override void Start() =>

Console.WriteLine("Car starts"); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, C# does not allow multiple class inheritance.
  • Use interfaces as a workaround.

interface IFlyable { void Fly(); }

interface IDriveable { void Drive(); }

class FlyingCar : IFlyable, IDriveable { public void Fly() {} public

void Drive() {} }

🔹 Section 8: Interfaces vs Abstract Classes – Interview

Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

Feature Abstract Class Interface

Implementation Can have full/partial

implementation

Cannot have full implementation (except

default methods in C# 8+)

Fields Can have fields Cannot have fields

Inheritance Single class inheritance Multiple interface inheritance allowed

Constructors Allowed Not allowed

Access

Modifiers

Can have public,

protected, private

Members are public by default

Permalink

C# OOP C# Programming Tutorial · OOP

  • When you want to define pure contracts without implementation.
  • When you need multiple inheritance.
  • When you want loose coupling for dependency injection.
Permalink

C# OOP C# Programming Tutorial · OOP

  • When you want to share common code among related classes.
  • When you need fields or constructors.
  • When future changes may require adding non-breaking methods.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes → Multiple interfaces
  • No → Multiple abstract classes (C# does not support multiple class inheritance)
Permalink

C# OOP C# Programming Tutorial · OOP

  • Interface allows multiple inheritance.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, starting from C# 8, interfaces can have default method implementations.

interface ILogger

void Log(string message);

void LogWarning(string message) => Console.WriteLine("Warning: "

+ message);

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can have fully implemented methods along with abstract

methods.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, both can define properties.
  • Interface properties are abstract by default; abstract class properties can have

implementation.

interface ICar { int Speed { get; set; } }

abstract class Vehicle { public int Speed { get; set; } }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, you cannot instantiate an interface.
  • You can only use it as a reference type.

ICar car = new Car(); // Interface reference

// ICar c = new ICar(); // Not allowed

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can be injected as service contracts, but interfaces are

preferred for looser coupling.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Both can define contracts for derived classes.
  • Both support polymorphism.
  • Both cannot be instantiated directly.
  • Both can be used with dependency injection.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Interface contracts are pure method signatures.
  • Abstract class contracts can contain shared code and fields.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Implementing class must provide implementation once.
  • Explicit interface implementation can resolve ambiguity.

interface IDriveable { void Start(); }

abstract class Vehicle { public abstract void Start(); }

class Car : Vehicle, IDriveable

public override void Start() => Console.WriteLine("Car

started");

Permalink

C# OOP C# Programming Tutorial · OOP

  • No, interfaces can only inherit other interfaces.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, abstract classes can implement interfaces partially or fully.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstract classes are slightly faster because they use direct method calls.
  • Interfaces may incur slight overhead due to indirect method calls via vtable.
  • Difference is usually negligible in most applications.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces are preferred for public APIs because they:
  • Allow multiple inheritance
  • Support loose coupling
  • Avoid breaking changes when adding new implementations
  • Abstract classes are better for internal APIs where shared code is required.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces: Adding new members breaks existing implementations unless using

default interface methods (C# 8+).

  • Abstract Classes: Can add new methods with implementation without breaking

derived classes.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Interfaces support multiple inheritance.
  • Abstract classes do not.

🔹 Section 9: Practical Scenarios & Design Questions –

Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Define an interface like IPlugin with a Run() method.
  • Each plugin implements IPlugin and can be loaded dynamically.

interface IPlugin { void Run(); }

class PluginA : IPlugin { public void Run() =>

Console.WriteLine("Plugin A running"); }

class PluginB : IPlugin { public void Run() =>

Console.WriteLine("Plugin B running"); }

// Usage

List<IPlugin> plugins = new List<IPlugin> { new PluginA(), new

PluginB() };

foreach (var p in plugins) p.Run();

Permalink

C# OOP C# Programming Tutorial · OOP

  • Use an interface for common operations: IPayment.
  • Use an abstract class for shared behavior like logging.

interface IPayment { void Pay(decimal amount); }

abstract class PaymentBase : IPayment

public abstract void Pay(decimal amount);

public void Log(string message) => Console.WriteLine(message);

class CreditCardPayment : PaymentBase

public override void Pay(decimal amount) =>

Console.WriteLine($"Paid {amount} by Credit Card");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Define a base Notification class or interface.
  • Derive classes like EmailNotification, SMSNotification.

abstract class Notification { public abstract void Send(string

message); }

class EmailNotification : Notification { public override void

Send(string msg) => Console.WriteLine("Email: " + msg); }

class SMSNotification : Notification { public override void

Send(string msg) => Console.WriteLine("SMS: " + msg); }

List<Notification> notifications = new List<Notification> { new

EmailNotification(), new SMSNotification() };

foreach (var n in notifications) n.Send("Hello World!");

Permalink

C# OOP C# Programming Tutorial · OOP

  • SOLID principles are design guidelines that enhance maintainability, flexibility,

and scalability of OOP systems.

  • They guide proper use of abstraction, inheritance, encapsulation, and

polymorphism.

Permalink

C# OOP C# Programming Tutorial · OOP

  • High-level modules should not depend on low-level modules. Both should depend

on abstractions.

  • Interfaces allow decoupling and easier testing.

interface ILogger { void Log(string message); }

class FileLogger : ILogger { public void Log(string message) =>

Console.WriteLine("File: " + message); }

class UserService

private readonly ILogger _logger;

public UserService(ILogger logger) { _logger = logger; }

Permalink

C# OOP C# Programming Tutorial · OOP

  • No client should be forced to implement methods it does not use.
  • Break large interfaces into smaller, focused interfaces.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Derived classes should be replaceable by base class without affecting

correctness.

  • Inheritance violating this principle can cause unexpected behavior.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Protects internal data by restricting direct access.
  • Ensures sensitive fields are accessed only via methods/properties, preventing

misuse.

Permalink

C# OOP C# Programming Tutorial · OOP

  • Use mocking frameworks like Moq or NSubstitute.
  • Provides fake implementations to test dependent classes.

var mockLogger = new Mock<ILogger>();

mockLogger.Setup(x => x.Log(It.IsAny<string>()));

Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstract class defines skeleton of algorithm.
  • Derived classes override steps without changing algorithm structure.

abstract class DataProcessor

public void Process() { ReadData(); Transform(); Save(); }

protected abstract void ReadData();

protected abstract void Transform();

protected void Save() => Console.WriteLine("Data saved");

Permalink

C# OOP C# Programming Tutorial · OOP

  • When behavior varies significantly.
  • When tight coupling or fragile base class problem may occur.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Hard to maintain and understand.
  • Fragile base class problem.
  • Overridden behavior may break subclasses.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Provides flexibility, reduces tight coupling, and avoids deep hierarchies.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Minor runtime overhead for virtual calls.
  • Usually negligible; design benefits outweigh performance cost.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use new interface or default implementations (C# 8+).
  • Avoid modifying existing interface to maintain backward compatibility.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstract Factory creates families of related objects.
  • Interfaces/abstract classes define product contracts, factories implement them.

interface IButton { void Render(); }

class WinButton : IButton { public void Render() =>

Console.WriteLine("Windows Button"); }

interface IGUIFactory { IButton CreateButton(); }

class WinFactory : IGUIFactory { public IButton CreateButton() =>

new WinButton(); }

Permalink

C# OOP C# Programming Tutorial · OOP

  • Base abstract class Shape with Draw() method.
  • Derived classes like Circle, Rectangle override Draw().
  • Supports polymorphic behavior.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Define abstract class FileHandler with method Read().
  • Derived classes CsvHandler, XmlHandler implement Read().
  • Use base class reference to process files uniformly.
Permalink

C# OOP C# Programming Tutorial · OOP

  • When you want to share code or fields across derived classes.
  • When common behavior is needed along with enforced methods.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Use composition or explicit interface implementation to avoid ambiguity.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Deep hierarchies, fragile base classes, tight coupling, misuse of override.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, adding new members can break existing implementations.
  • Use default interface methods to avoid breaking changes.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Allows dependency injection of mocks/stubs.
  • Enables unit testing without relying on concrete implementations.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Virtual calls resolved at runtime.
  • Minor overhead due to vtable lookups, generally negligible.
Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, interfaces can define event contracts for publishers/subscribers.
  • Enables decoupling of event producers and consumers.

🔹 Questions (Advanced Topics) – Interview Q&A

Permalink

C# OOP C# Programming Tutorial · OOP

  • Duck typing: "If it looks like a duck and quacks like a duck, it is a duck."
  • Behavior is based on method/property availability, not type inheritance.
  • C# does not support full dynamic duck typing, but interfaces enable a similar

concept by relying on contract-based behavior.

  • Dynamic types in C# (dynamic) can also simulate duck typing.

interface IFlyable { void Fly(); }

void MakeItFly(IFlyable obj) => obj.Fly(); // Any object

implementing IFlyable works

Permalink

C# OOP C# Programming Tutorial · OOP

  • Yes, C# 8 introduced private methods in interfaces.
  • Purpose: share implementation among default interface methods without

exposing them publicly.

interface ILogger

void Log(string message) => LogInternal(message);

private void LogInternal(string msg) => Console.WriteLine(msg);

Permalink

C# OOP C# Programming Tutorial · OOP

  • Allows interfaces to provide default method implementations.
  • Reason: Enables adding new methods to interfaces without breaking existing

implementations.

interface IPrinter

void Print(string msg);

void PrintInfo(string msg) => Console.WriteLine("Info: " + msg);

// Default

Permalink

C# OOP C# Programming Tutorial · OOP

  • Abstract classes often define base contracts or template methods for patterns:
  • Abstract Factory: Defines abstract methods to create families of objects.
  • Strategy Pattern: Abstract class defines a common interface for

interchangeable algorithms.

abstract class PaymentStrategy

public abstract void Pay(decimal amount);

class CreditCardPayment : PaymentStrategy

public override void Pay(decimal amount) =>

Console.WriteLine($"Paid {amount} by credit card");

Permalink

C# OOP C# Programming Tutorial · OOP

  • Encapsulation and abstraction hide implementation details, exposing only

necessary interfaces.

  • Polymorphism allows replaceable modules, facilitating microservices

independently deployed and evolved.

  • SOLID principles and interface-based contracts promote loose coupling and

autonomous service design.

Permalink