Inheritance is a key concept in object-oriented programming where one class inherits the properties and behaviors of another class. In C#, a derived class can inherit from a single base class using the “colon” syntax.
For example, let’s say we have a base class called “Animal” that defines common properties and behaviors of all animals:
“`
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public void Eat()
{
Console.WriteLine(“The animal is eating.”);
}
public virtual void Sound()
{
Console.WriteLine(“The animal is making a sound.”);
}
}
“`
Now, we can define a derived class called “Cat” that inherits from the “Animal” class:
“`
public class Cat : Animal
{
public void Meow()
{
Console.WriteLine(“The cat says meow.”);
}
public override void Sound()
{
Console.WriteLine(“The cat is purring.”);
}
}
“`
The “Cat” class now has access to all the properties and methods of the “Animal” class. It also has its own unique methods, such as “Meow”. In addition, it can override the virtual method “Sound” defined in the base class to provide its own implementation.
Polymorphism is another important concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. In C#, this is achieved using inheritance and the “base” keyword.
For example, let’s say we have a method called “MakeSound” that accepts an object of the “Animal” class as a parameter:
“`
public void MakeSound(Animal animal)
{
animal.Sound();
}
“`
We can now pass objects of different derived classes to this method:
“`
Animal animal1 = new Animal();
Cat cat1 = new Cat();
MakeSound(animal1); // The animal is making a sound.
MakeSound(cat1); // The cat is purring.
“`
Notice how the “MakeSound” method can accept both an object of the “Animal” class and an object of the “Cat” class. This is possible because the “Cat” class inherits from the “Animal” class and can be treated as an “Animal” object.
In summary, inheritance and polymorphism are powerful concepts in C# that allow for code reusability and flexibility in object-oriented programming. By defining a base class and deriving new classes from it, we can create a hierarchy of related classes with shared properties and behaviors. By using polymorphism, we can treat objects of derived classes as objects of their base class, allowing for more generic and flexible code.