Sunday, 30 November 2025

Can an Abstract Class Have a Constructor?

Can an Abstract Class Have a Constructor?

Yes — an abstract class can have a constructor in C#.

Why an Abstract Class Constructor is Allowed in C#

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

C# Code Example: Abstract Class Constructor with base()

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

In C#, both abstract classes and interfaces handle abstraction differently: abstract classes share base code and state among related types, while interfaces define a contract of capabilities across unrelated types.

What Are Abstract Classes and Interfaces?

  • Abstract class: An uninstantiable class (using abstract) supporting both abstract and concrete members.
  • Interface: A contract (using interface) dictating required members without dictating internal implementation.

Abstract Class vs Interface: Key Differences

Aspect Abstract Class Interface
Members & State Abstract and concrete methods/properties; can hold instance or static fields. Signatures only (though C# 8+ allows default implementations); no instance fields.
Modifiers & Setup Supports standard access modifiers; can define constructors. Members are implicitly public; cannot have constructors.
Inheritance Single class inheritance only. Multiple interface implementation supported.
Use Case "Is-a" relationship for shared base logic. "Can-do" relationship for cross-cutting capabilities.

When to Use Abstract Class vs Interface

  • Abstract class: Best for closely related classes sharing base behavior or state to eliminate duplicate code.
  • Interface: Best for defining flexible contracts across disparate, unrelated types.

C# Code Example: Using Both Together

abstract class Animal
{
    public string Name;
    public abstract void MakeSound();
    public void Sleep() { Console.WriteLine("Sleeping..."); }
}

interface IWalker
{
    void Walk();
}

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

How This Example Works

  • Animal provides shared state and concrete logic (Sleep()).
  • IWalker enforces the walking contract.
  • Dog combines both through single class inheritance and interface implementation.

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?

An abstract class in C# serves as an uninstantiable base class containing both abstract members (without implementation) and concrete members (with implementation) for derived classes to inherit.

Key Features of Abstract Classes in C#

  • No Direct Instantiation: Prevents creating objects directly via new.
  • Abstract & Concrete Members: Supports abstract declarations alongside standard implemented methods.
  • Enforces Base Structure: Guarantees derived classes implement all required abstract members.

Important Rules to Remember

  • Use the override Keyword: Derived non-abstract classes must use override to implement inherited abstract methods.
  • Can Have Constructors: Abstract classes can define constructors to initialize shared fields (see Can an Abstract Class Have a Constructor?).
  • Single Inheritance Only: A C# class can inherit from only one abstract class at a time.

C# Abstract Class Code Example

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

    public void Sleep()               // concrete method (with body)
    {
        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 instantiate Dog, which inherits Sleep() and implements MakeSound().

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#

This C# tutorial demonstrates runtime polymorphism using the virtual and override keywords with a Car and SportsCar class structure.

C# Function Overriding Code 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()
    {
        new Car().Start();
        new SportsCar().Start();
        Car carRef = new SportsCar();
        carRef.Start();
    }
}

Console Output

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

How This Example Works (Step-by-Step)

  • Virtual & Override: The base Car.Start() is marked virtual, allowing SportsCar to replace it via override.
  • Runtime Polymorphism: A base reference pointing to a derived instance (Car carRef = new SportsCar()) executes the overridden method at runtime, contrasting with Method Hiding in C#.

Static Binding in C#

Static binding, also called early binding, occurs when the compiler determines which method to execute at compile time. It is used in compile-time polymorphism, such as method overloading and operator overloading.

Key Points of Static Binding in C#

  • Resolved at Compile Time: The C# compiler matches the method signature before the program runs.
  • Used in Overloading: Occurs in method overloading, operator overloading, and private, static, or sealed method calls.
  • Faster Execution: Requires less runtime overhead than dynamic binding because the target method is already known.
  • Opposite of Dynamic Binding: Contrasts with late binding used in method overriding (see Dynamic Binding in C#).

C# Static Binding Code Example (Method Overloading)

using System;

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));     // Calls int Add(int, int)
        Console.WriteLine(calc.Add(2.5, 3.5)); // Calls double Add(double, double)
    }
}

Console Output

5
6

How This Example Works

  • Signature Matching: Passing integers (2, 3) binds directly to Add(int, int) during compilation.
  • Overload Resolution: Passing floating-point values (2.5, 3.5) binds to Add(double, double) without waiting for runtime.