Saturday, May 13, 2023

Types of inheritance in c#| inheritance in c#| inheritance types in c#

 Types of inheritance in c#


In C#, there are several types of inheritance that can be used to create a hierarchy of classes:


1. Single inheritance: This is the simplest and most common type of inheritance. In single inheritance, a class inherits from a single base class. For example:



class Animal

{

    public void Eat()

    {

        Console.WriteLine("The animal is eating");

    }

}


class Dog : Animal

{

    public void Bark()

    {

        Console.WriteLine("The dog is barking");

    }

}



In this example, the "Dog" class inherits from the "Animal" class.


2. Multi-level inheritance: This occurs when a derived class inherits from a base class that itself inherits from another base class. For example:



class Animal

{

    public void Eat()

    {

        Console.WriteLine("The animal is eating");

    }

}


class Mammal : Animal

{

    public void DrinkMilk()

    {

        Console.WriteLine("The mammal is drinking milk");

    }

}


class Dog : Mammal

{

    public void Bark()

    {

        Console.WriteLine("The dog is barking");

    }

}



In this example, the "Mammal" class inherits from the "Animal" class, and the "Dog" class inherits from the "Mammal" class.


3. Hierarchical inheritance: This occurs when two or more derived classes inherit from a single base class. For example:



class Animal

{

    public void Eat()

    {

        Console.WriteLine("The animal is eating");

    }

}


class Dog : Animal

{

    public void Bark()

    {

        Console.WriteLine("The dog is barking");

    }

}


class Cat : Animal

{

    public void Meow()

    {

        Console.WriteLine("The cat is meowing");

    }

}



In this example, both the "Dog" and "Cat" classes inherit from the "Animal" class.


4. Multiple inheritance (not supported in C#): This occurs when a class inherits from two or more base classes. However, C# does not support multiple inheritance directly. Instead, you can achieve similar functionality using interfaces, which are similar to abstract classes that define a contract that implementing classes must follow.


In summary, the types of inheritance in C# include single inheritance, multi-level inheritance, and hierarchical inheritance. While multiple inheritance is not supported in C#, you can use interfaces to achieve similar functionality.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...