Sunday, 30 November 2025

Can an Abstract Class Have a Constructor?

Can an Abstract Class Have a Constructor?

Can an Abstract Class Have a Constructor?

Yes — an abstract class can have a constructor in C#. :contentReference[oaicite:0]{index=0}

Why it’s allowed (and useful)

  • Even though you can’t instantiate the abstract class itself, constructors in it are called when a concrete subclass is instantiated. :contentReference[oaicite:1]{index=1}
  • That constructor allows initialization of fields or shared setup logic common to all subclasses. :contentReference[oaicite:2]{index=2}
  • In C#, such constructors are often marked protected (or internal/protected internal), so they can only be used by subclasses — not from outside. :contentReference[oaicite:3]{index=3}

Example in C# + HTML-style illustration

abstract class Shape
{
    public string Color { get; }

    // Constructor of the abstract class
    protected Shape(string color)
    {
        Color = color;
        Console.WriteLine($"Shape created with color {color}");
    }

    public abstract double CalculateArea();
}

class Square : Shape
{
    public double Side { get; }

    public Square(string color, double side) : base(color)
    {
        Side = side;
    }

    public override double CalculateArea()
    {
        return Side * Side;
    }
}

class Program
{
    static void Main()
    {
        Square square = new Square("red", 5);
        Console.WriteLine($"Area of square: {square.CalculateArea()}");
    }
}
    

In this example, Shape is declared abstract and defines a constructor that initializes a Color property. The derived class Square calls that constructor using : base(color). When new Square(...) is executed, Shape’s constructor runs first (to initialize shared data), then Square’s constructor completes.

Abstract Class vs Interface

Abstract Class vs Interface — Comparison

Abstract Class vs Interface (in C#)

What they are

  • Abstract class: a special class (declared with the abstract keyword) that cannot be instantiated. It can include both abstract members (without implementation) and concrete members (with implementation).
  • Interface: a contract (declared with the interface keyword) describing a set of members (methods, properties, events, indexers) that implementing classes/structs must provide. It describes “what” must be done, not “how.”

Key Differences

AspectAbstract ClassInterface
Members Can have both abstract (no body) and concrete (with body) methods/properties, and even fields. :contentReference[oaicite:0]{index=0} Members are (mostly) just declarations (method/property signatures). In older versions, no implementation. Modern C# (from C# 8) allows default implementations and static members, but interfaces still cannot have instance fields. :contentReference[oaicite:1]{index=1}
Fields / State Can have fields (instance or static), so can hold state. :contentReference[oaicite:2]{index=2} Cannot have instance fields. Interfaces are not meant to hold state. :contentReference[oaicite:3]{index=3}
Access Modifiers Members can have access modifiers (public, protected, private, etc.). :contentReference[oaicite:4]{index=4} Members are implicitly public (in C#), and you normally cannot specify other access modifiers. :contentReference[oaicite:5]{index=5}
Constructors Can have constructors (to initialize state, etc.). :contentReference[oaicite:6]{index=6} Cannot have constructors because interfaces cannot be instantiated directly. :contentReference[oaicite:7]{index=7}
Inheritance / Implementation A class can inherit from only one abstract class (single inheritance). :contentReference[oaicite:8]{index=8} A class or struct can implement multiple interfaces (multiple-interface implementation). :contentReference[oaicite:9]{index=9}
Typical Use Case Useful when you want to share common code or behavior among related classes, or maintain common state. Good for “is-a” relationships. :contentReference[oaicite:10]{index=10} Useful when you just want to define a capability (a contract) that many unrelated classes can implement. Good for “can-do” or “has capability” relationship. :contentReference[oaicite:11]{index=11}

When to Use What

  • If you have a group of closely related classes that share common behaviour or state, and you want to avoid code duplication — use an abstract class.
  • If you want to define a contract (a set of capabilities) that many different, possibly unrelated classes should implement — use an interface.
  • Because interfaces support multiple implementation, they are more flexible when you need to combine many capabilities across different types.
  • Abstract classes are better when you want to provide default behavior or base implementations that subclasses can reuse or extend.

Example in C#

abstract class Animal {
    public string Name;             // field

    public abstract void MakeSound(); // abstract method

    public void Sleep() {             // concrete method
        Console.WriteLine("Sleeping...");
    }
}

interface IWalker {
    void Walk();  // method signature only
}

class Dog : Animal, IWalker {
    public override void MakeSound() {
        Console.WriteLine("Bark!");
    }

    public void Walk() {
        Console.WriteLine("Dog is walking...");
    }
}
  

In this example:
Animal is an abstract class — it provides shared code (the Sleep() method) and a field (Name).
IWalker is an interface — it defines a “capability” (walking).
Dog inherits from Animal and implements IWalker, so it gets the common behavior and commits to supporting walking.

What Is an Interface?

What Is an Interface?

What Is an Interface in C#?

An interface in C# is a contract that defines a set of methods, properties, events, or indexers—without providing any implementation. A class or struct that implements an interface must provide the implementation for all its members.

Key Features of Interfaces

  • Cannot contain implementation (except default interface methods in newer C# versions).
  • A class can implement multiple interfaces (supports multiple inheritance).
  • Defines “what” a class should do, not “how” it should do it.
  • Members are public by default.

Example in C#

interface IAnimal
{
    void MakeSound();   // method without implementation
    void Sleep();       // another method
}

class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Bark!");
    }

    public void Sleep()
    {
        Console.WriteLine("Sleeping...");
    }
}
    

Here, IAnimal is an interface that declares two methods. The Dog class implements this interface and provides the actual method bodies.

What is an abstract class?

What Is an Abstract Class?

What Is an Abstract Class?

An abstract class in C# is a class that cannot be instantiated. It is intended to be a base class that other classes inherit from. Abstract classes can contain both abstract members (without implementation) and concrete members (with implementation).

Key Features of Abstract Classes in C#

  • Cannot be instantiated directly.
  • May contain abstract methods, properties, or indexers.
  • Can contain fully implemented methods.
  • Used to enforce a base structure for derived classes.

Example in C#

abstract class Animal
{
    public abstract void MakeSound(); // abstract method

    public void Sleep()               // normal method
    {
        Console.WriteLine("Sleeping...");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark!");
    }
}
    

In this example, Animal is an abstract class. You cannot create new Animal(), but you can create Dog, which inherits and implements the abstract method.

Monday, 17 November 2025

Method Hiding in C#

Method Hiding in C#

Method Hiding

Method hiding occurs when a derived class defines a method with the same name as a method in the base class but uses the new keyword. The version of the method called depends on the reference type.

C# Example:

using System; class Car { public void Start() { Console.WriteLine("Car is starting."); } } class SportsCar : Car { public new void Start() { Console.WriteLine("SportsCar is starting with turbo!"); } } class Program { static void Main() { Car carRef = new Car(); carRef.Start(); SportsCar sportsCarRef = new SportsCar(); sportsCarRef.Start(); Car baseRef = new SportsCar(); baseRef.Start(); } }

Output:

Car is starting. SportsCar is starting with turbo! Car is starting.

Function Overriding Example in C#

Function Overriding Example in C#

Function Overriding Example

In this example, the Start method is overridden in the derived class SportsCar using the override keyword. This demonstrates runtime polymorphism.

C# Example:

using System; class Car { public virtual void Start() { Console.WriteLine("Car is starting."); } } class SportsCar : Car { public override void Start() { Console.WriteLine("SportsCar is starting with turbo!"); } } class Program { static void Main() { Car myCar = new Car(); myCar.Start(); SportsCar mySportsCar = new SportsCar(); mySportsCar.Start(); Car carRef = new SportsCar(); carRef.Start(); } }

Output:

Car is starting. SportsCar is starting with turbo! SportsCar is starting with turbo!

Static Binding in C#

Static Binding in C#

Static Binding

Static binding, also called early binding, means that the method to be executed is determined at compile time. It is used in compile-time polymorphism such as method overloading and operator overloading.

Key Points:

  • Resolved at compile time.
  • Occurs in method overloading or operator overloading.
  • Faster than dynamic binding.
  • Opposite of dynamic (late) binding.

C# Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } } class Program { static void Main() { Calculator calc = new Calculator(); Console.WriteLine(calc.Add(2, 3)); Console.WriteLine(calc.Add(2.5, 3.5)); } }

Output:

5 6

Dynamic Binding in C#

Dynamic Binding in C#

Dynamic Binding

Dynamic binding, also known as late binding, means that the method to execute is determined at runtime based on the actual object being referred to. It is used in runtime polymorphism.

Key Points:

  • Resolved at runtime.
  • Occurs during method overriding.
  • Requires virtual and override.
  • Base class reference can call derived class methods.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving fast!

Function Overriding in C#

Function Overriding in C#

Function Overriding

Function overriding means defining the same method in a derived class that already exists in the base class, using the same name, parameters, and return type. It is used to change the inherited behavior.

Key Points

  • Requires virtual in the base class.
  • Requires override in the derived class.
  • Method name, parameters, and return type must match exactly.
  • Used for runtime polymorphism.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving very fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving very fast!

Operator Overloading in C#

Operator Overloading in C#

Operator Overloading in C#

Operator overloading allows developers to redefine the behavior of operators (like +, -, *, ==) for custom classes and structs. It makes objects behave like built-in types when using operators.

Key Points:

  • Uses the operator keyword.
  • Must be defined inside a class or struct.
  • At least one parameter must be a user-defined type.

C# Example:

class CarSpeed { public int Speed { get; set; } public CarSpeed(int speed) { Speed = speed; } public static CarSpeed operator +(CarSpeed c1, CarSpeed c2) { return new CarSpeed(c1.Speed + c2.Speed); } } class Program { static void Main() { CarSpeed car1 = new CarSpeed(60); CarSpeed car2 = new CarSpeed(40); CarSpeed total = car1 + car2; Console.WriteLine("Total Speed: " + total.Speed); } }

Output:

Total Speed: 100

Overloading Main Method

Overloading Main Method

Can You Overload the Main Method in C#?

Yes, you can overload the Main method in C#, but only one serves as the program's entry point.

Example:

class Program { static void Main(string[] args) { Console.WriteLine("Main with string[] args"); Main(10); } static void Main(int number) { Console.WriteLine("Overloaded Main with int: " + number); } static void Main(double value) { Console.WriteLine("Overloaded Main with double: " + value); } }

Key Points:

  • You can overload Main like any other method.
  • Only one method is used as the entry point.
  • Overloaded Main methods must be called manually.

Compile-time Polymorphism

Compile-time Polymorphism

Compile-time Polymorphism in C#

Compile-time polymorphism, also called static polymorphism, means that the method to be executed is decided during compile time. It is mainly achieved through method overloading in C#.

Features:

  • Decided at compile time
  • Achieved using method overloading
  • Occurs within the same class
  • Faster than runtime polymorphism

C# Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } } class Program { static void Main() { Calculator c = new Calculator(); Console.WriteLine(c.Add(2, 3)); Console.WriteLine(c.Add(2.5, 3.1)); Console.WriteLine(c.Add(1, 2, 3)); } }

Runtime Polymorphism

Runtime Polymorphism

Runtime Polymorphism in C#

Runtime polymorphism (dynamic polymorphism) means that the method to be executed is decided during runtime. It is achieved through method overriding using the virtual and override keywords.

Features:

  • Achieved using method overriding
  • Uses virtual and override
  • Method selection happens at runtime
  • Enables dynamic and flexible behavior

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving fast!

Overloading vs Overriding

Overloading vs Overriding

Difference Between Overloading and Overriding in C#

1. Method Overloading

  • Same method name, different parameters.
  • Occurs within the same class.
  • Compile-time (static) polymorphism.
  • Parameters must change (type, number, or order).

C# Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } }

2. Method Overriding

  • Same method name, same parameters.
  • Occurs in different classes using inheritance.
  • Runtime (dynamic) polymorphism.
  • Uses virtual and override keywords.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving"); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving fast!"); } }

C# Inheritance Concepts

C# Inheritance Concepts

C# Inheritance & Keywords

1. The sealed Keyword (C# version of Java's final)

C# does not use the keyword final. Instead, it uses sealed to:

  • Stop a class from being inherited
  • Stop a method from being overridden again

Sealed Class Example

sealed class Car { }

Sealed Method Example

class A { public virtual void Show() { } } class B : A { public sealed override void Show() { } }

2. Multilevel Inheritance Example Using Car Classes

Multilevel inheritance means:

Car → SportsCar → RaceCar

C# Example

class Car // Level 1 (Base Class) { public void Start() { Console.WriteLine("Car starts."); } } class SportsCar : Car // Level 2 (Inherits from Car) { public void Turbo() { Console.WriteLine("SportsCar activates turbo."); } } class RaceCar : SportsCar // Level 3 (Inherits from SportsCar) { public void Nitro() { Console.WriteLine("RaceCar boosts with nitro!"); } } class Program { static void Main() { RaceCar rc = new RaceCar(); rc.Start(); // from Car rc.Turbo(); // from SportsCar rc.Nitro(); // from RaceCar } }

Output:

Car starts. SportsCar activates turbo. RaceCar boosts with nitro!

Saturday, 15 November 2025

Multiple Inheritance in C#

Multiple Inheritance in C#

Can a Class Inherit from Multiple Classes in C#?

No. In C#, a class cannot inherit from more than one class directly. This restriction is in place to avoid ambiguity problems such as the diamond problem that can occur in multiple inheritance.

Example (Not Allowed)

class A { }
class B { }

class C : A, B { }  // ❌ This is NOT allowed in C#
    

How C# Handles Multiple Inheritance

  • C# supports multiple inheritance via interfaces. A class can implement multiple interfaces.
  • This avoids ambiguity because interfaces only define method signatures, and the implementing class provides the actual implementation.

Example Using Interfaces

interface IA {
    void MethodA();
}

interface IB {
    void MethodB();
}

class C : IA, IB {
    public void MethodA() {
        Console.WriteLine("MethodA implementation");
    }

    public void MethodB() {
        Console.WriteLine("MethodB implementation");
    }
}
    

Summary: C# does not allow multiple class inheritance, but multiple interfaces can be implemented to achieve similar behavior.

The 'base' Keyword in C#

The 'base' Keyword in C#

The base Keyword in C#

In C#, the base keyword is used to refer to the immediate parent class of the current class. It is similar to the super keyword in Java.

Main Uses of base

  1. Access parent class methods: Call a method in the base class that is overridden in the derived class.
  2. Access parent class constructors: Invoke a constructor of the base class from the derived class constructor.
  3. Access parent class properties or fields: Access members of the base class that are hidden in the derived class.

Examples

1. Calling Base Class Method

class Parent {
    public void Show() {
        Console.WriteLine("Parent Show");
    }
}

class Child : Parent {
    public new void Show() {
        Console.WriteLine("Child Show");
    }

    public void Display() {
        base.Show(); // calls Parent's Show()
    }
}
    

2. Calling Base Class Constructor

class Parent {
    public Parent() {
        Console.WriteLine("Parent Constructor");
    }
}

class Child : Parent {
    public Child() : base() {  // calls Parent constructor
        Console.WriteLine("Child Constructor");
    }
}
    

Note: Use base when you want to explicitly access members or constructors of the parent class from a derived class.

Diamond Problem in Inheritance

Diamond Problem in Inheritance

The Diamond Problem

The diamond problem occurs in multiple inheritance when a class inherits from two classes that both inherit from a common base class. This creates ambiguity about which base class method or property should be used.

Illustration of the Diamond Problem

        A
       / \
      B   C
       \ /
        D
    

Here:

  • Class A is the base class.
  • Classes B and C inherit from A.
  • Class D inherits from both B and C.

Problem: If A has a method Show() and both B and C override it, which version should D inherit? This ambiguity is called the diamond problem.

How C# Handles It

  • C# does not allow multiple class inheritance, so the diamond problem is avoided for classes.
  • Using interfaces, C# allows multiple inheritance without ambiguity because interface methods must be explicitly implemented.

Example with Interfaces in C#

interface IA {
    void Show();
}

interface IB : IA { }
interface IC : IA { }

class D : IB, IC {
    public void Show() {
        Console.WriteLine("Implemented Show in D");
    }
}
    

Here, D explicitly implements the method, resolving any ambiguity.

Types of Inheritance in C#?

Types of Inheritance in C#

Inheritance is a mechanism where one class (derived class) acquires the properties and behaviors of another class (base class). C# supports several types of inheritance:

1. Single Inheritance

A derived class inherits from only one base class.

class Base {
    public void Show() { }
}

class Derived : Base {
    // inherits Show() from Base
}
    

2. Multilevel Inheritance

A class is derived from another derived class, forming a chain.

class GrandParent { }
class Parent : GrandParent { }
class Child : Parent { }
    

3. Hierarchical Inheritance

Multiple classes inherit from a single base class.

class Base { }
class Child1 : Base { }
class Child2 : Base { }
    

4. Multiple Inheritance (via Interfaces)

C# does not support multiple class inheritance directly, but multiple interfaces can be implemented.

interface IA { }
interface IB { }

class Derived : IA, IB { }
    

5. Hybrid Inheritance

A combination of two or more types of inheritance. In C#, achieved using interfaces along with classes.

interface IA { }
class Base { }
class Derived : Base, IA { }
    

Note: C# allows single, multilevel, hierarchical, and hybrid inheritance using interfaces, but not direct multiple class inheritance.

Difference Between Encapsulation and Abstraction?

Encapsulation vs Abstraction

Encapsulation

  • Encapsulation is about hiding data and protecting it from outside access.
  • It bundles data and methods into a single unit (e.g., a class).
  • Achieved using access modifiers like private, protected, etc.
  • Controls how data is accessed or modified.
class Person {
    private int age; // hidden data

    public void SetAge(int value) { // controlled access
        if (value >= 0) age = value;
    }
}
    

Abstraction

  • Abstraction is about hiding complexity and showing only essential features.
  • Lets you focus on what something does rather than how it works.
  • Achieved using abstract classes and interfaces.
abstract class Animal {
    public abstract void MakeSound(); // only essential behavior shown
}
    

Summary

Encapsulation Abstraction
Hides internal data Hides implementation complexity
Protects the data Simplifies the design

Encapsulation = hiding data
Abstraction = hiding complexity