C# Fundamentals - Classes -Inheritance

C# Fundamentals - Classes -Inheritance

Β·

6 min read

What is?

In C#, inheritance is the ability that allows a class (called the child or derived class) to use all methods and properties from another class (called the base class or parent).

Why is it useful?

Being able to inherit properties and methods from other classes, helps in reusing code, organizing it neatly, and making it easier to understand and update.

It's like building upon existing knowledge and making new things out of it, without starting from scratch each time (and I would say this is a good reason).

Are there any disadvantages? πŸ‘€

Yes πŸ˜“, depending on the code, this could lead to tight coupling between the base and derived classes, meaning any changes made in the base will affect the child (for the good and bad). Also with multiple levels of inheritance, the code can become more complex and hard to understand.

Ok! But How do I implement inheritance in C#?

Simple! Let's create a situation as an example.

So in this example, we have a base class called Animal (pretty much general) that Eats and Sleeps (the methods), then you want to create a new class called Dog, with its method Bark but also sleeps and eats, so the easiest is to inherit the methods from Animal.

To do that let's first declare the class Animal:

// Base class
public class Animal 
{
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }

    public void Sleep()
    {
        Console.WriteLine("Animal is sleeping.");
    }
}

Now we will create a class Dog using ":" to say it will inherit from the Animal class:

 public class Dog : Animal // this is the away to create inheritance between classes.
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}
class Program
{
    static void Main()
    {
        Dog Akita = new Dog()
        Akita.Eat() //Animal is eating.
    }
}

But then you will ask...

How do I handle constructors with parameters (arguments) when implementing inheritance in C#? πŸ€”

To inherit a Constructor from the Base class, we use base the keyword followed by the arguments (parameter list) of the Base class's Constructor. The base keyword will connect the arguments from the child to the parameters from the Base's Constructor.

Am I obligated to declare a Constructor in the Derived class?

If the Base hasn't declared a Constructor with parameters you don't need to declare it in the Derived class (if not necessary).

However, if the Base has Constructor (s) with parameters, you will need to declare it in the Derived (at least 1 of Base's Constructors).


//Base class
public class Shape
{
    public int SideX { get; set; }
    public int SideY { get; set; }
    public double Area;
    //Base Constructor:
    public Shape( int sideX, int sideY) 
    {
        SideX = sideX;
        SideY = sideY;
        CalcArea();
    }
    public virtual void CalcArea ()
    { Area =  SideX*SideY;}
}

//Derived Class
public class Rectangle : Shape // Retangle inherit from Shape
{
//if the Base class has a constructor with parameters, you will have to declare it in the Child as well.
    public Rectangle(int sideX, int sideY) : base(sideX, sideY) { } // To inherit Constructor from Base class

    public void SideDifference()
    {
        int calcSide;
        if (SideX > SideY)
        {calcSide = SideX - SideY;}
        else
        {calcSide = SideY - SideX;}
        Console.WriteLine(calcSide);
    }
}

Check below the other scenarios between Base Constructor and Derived:

1 - Base is not declaring Constructor, while Derived is declaring its own Constructor.

In this situation, the Base class is not declaring a Constructor, so if the Derived needs a specific constructor, this will be declared normally.


public class Animal
{
    public void Eat()
    {Console.WriteLine("Animal is eating.");}
    public void Sleep()
    {Console.WriteLine("Animal is sleeping.");}
}

public class Dog : Animal // this is the away to create inheritance between classes.
{
    public string Name { get; set; }

 // Declaring a Constructor specific for Dog class
    public Dog (string name)
    {Name = name;}
    public void Bark()
    {Console.WriteLine($" {Name} is barking.");}
}
class Program
{
    static void Main()
    {
        Dog Akita = new Dog("Lulu");
        Akita.Eat(); //Animal is eating.
        Akita.Bark();//Lulu is barking.
    }
}

2- Base is declaring Constructor, while Derived is inheriting it and adding its own arguments.

In this case Base class has a Constructor that calls arguments and the derived class will inherit this constructor, and also add its own arguments.

//Base class
public class Shape
{
    public int SideX { get; set; }
    public int SideY { get; set; }
    public double Area;
    public Shape( int sideX, int sideY) 
    {
        SideX = sideX;
        SideY = sideY;
        CalcArea();
    }
    public virtual void CalcArea () //virtual allow to override the method if necessary.
    {Area =  SideX*SideY;}
}

//Creating the derivaded class
public class Trapezoid : Shape
{
    public int Height { get; set; }
    //Costructor
    // When the Child need more argumets not provided by the Prent
    public Trapezoid(int sideX, int sideY, int height) : base(sideX, sideY) 
    { 
        Height = height;
        CalcArea();// remember to call the method again as you Override it.
    }

    public override void CalcArea()// override is used to re-wrtie the method functionality.
    {Area = (SideX+SideY)/2.0 * Height;}
}


class Program
{
    static void Main()
    {
        Shape myShape = new Shape(4, 5);
        Console.WriteLine( myShape.Area); //20

        Trapezoid myTrapezoid = new Trapezoid(2,4 ,2 );
        Console.WriteLine( myTrapezoid.Area); //6
    }
}

3- Base is declaring Constructor that accepts 2 (or more) parameters, while Derived just needs 1.

There are situations where the base class may have a constructor that accepts multiple parameters, while the derived class may only need one parameter. This scenario commonly occurs when the derived class only needs to provide values for some of the parameters required by the base class constructor, and the remaining parameters have default values or are derived from other sources.

public class Shape
{
    public int SideX { get; set; }
    public int SideY { get; set; }
    public double Area;

    // Base class constructor accepting two parameters
    public Shape(int sideX, int sideY)
    {
        SideX = sideX;
        SideY = sideY;
        CalcArea();
    }
    public virtual void CalcArea()
    {Area = SideX * SideY;}
}

public class Square : Shape
{// Derived class constructor requiring only one parameter
    public Square(int side) : base(side, side)
}

class Program
{
    static void Main()
    {
        Shape myShape = new Shape(4, 5);
        Console.WriteLine( myShape.Area); //20

        Square mySquare = new Square(4);
        Console.WriteLine( mySquare.Area); //16
    }
}

In this code, the Square class constructor takes only one parameter (side). When this constructor is called, it invokes the base class constructor using base(side, side).

Bypassing the same value side for both SideX and SideY, we effectively initialize the Shape class properties in the Square class constructor. This ensures that a Square object is properly initialized with equal values for both sides.

To learn more about C# Fundamentals...

< Tag along /> ✧ ( β€’ α΄— - ) ✧

Did you find this article valuable?

Support Marcia Satie by becoming a sponsor. Any amount is appreciated!

Β