Saturday, May 13, 2023

Inheritance in C#| c# inheritance| inheritance

What is an inheritance in c#?


 Inheritance is a fundamental concept in object-oriented programming (OOP) and is supported in C#. Inheritance allows a new class to be based on an existing class, inheriting all the properties and methods of the existing class. The new class is called the derived class, and the existing class is called the base class.


When a class inherits from another class, it automatically acquires all the data members and member functions of the base class, and it can also add its own unique data members and member functions. This is known as code reuse and is a powerful way to create complex systems while keeping the code organized and manageable.


To implement inheritance in C#, the derived class is declared using a colon (:) followed by the name of the base class. Here is an example:



class Animal // Base class

{

    public void Eat()

    {

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

    }

}


class Dog : Animal // Derived class

{

    public void Bark()

    {

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

    }

}



In this example, the base class is "Animal" and the derived class is "Dog". The "Dog" class inherits the "Eat" method from the "Animal" class and adds its own "Bark" method.


Now, we can create an object of the "Dog" class and call its methods, including the inherited "Eat" method:



Dog dog = new Dog();

dog.Eat(); // inherited from Animal class

dog.Bark(); // defined in Dog class



In summary, inheritance is a powerful mechanism in C# that allows a new class to be based on an existing class, inheriting its properties and methods and adding its own unique features. This makes code reuse and organization easier and more efficient.

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...