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