Inheritance in C# allows a class (called derived class) to acquire properties and methods from another class (called base class). It promotes code reusability and makes applications easier to maintain.
class DerivedClass : BaseClass
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
class Program
{
static void Main()
{
Dog myDog = new Dog();
myDog.Eat(); // Inherited from Animal
myDog.Bark(); // Defined in Dog
}
}
class Animal
{
public void Eat() => Console.WriteLine("Eating...");
}
class Mammal : Animal
{
public void Walk() => Console.WriteLine("Walking...");
}
class Human : Mammal
{
public void Speak() => Console.WriteLine("Speaking...");
}
class Program
{
static void Main()
{
Human person = new Human();
person.Eat(); // From Animal
person.Walk(); // From Mammal
person.Speak(); // From Human
}
}
Use base
to access members of the base class from the derived class.
class Vehicle
{
public Vehicle()
{
Console.WriteLine("Vehicle constructor");
}
}
class Car : Vehicle
{
public Car() : base()
{
Console.WriteLine("Car constructor");
}
}
Car
is created, the base class constructor Vehicle()
runs first.
: BaseClass
to inheritbase
keyword to call base class membersHelp others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!