Inheritance is a feature that lets one class pick up and use the fields/properties/methods of another class. You write common behavior once in a base class, and derived classes can reuse it, which cuts down on repeated code.
csharp
class Vehicle
{
public string Brand = "Ford";
public void Start()
{
Console.WriteLine("Vehicle started");
}
}
class Car : Vehicle
{
public string ModelName = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();
Console.WriteLine(myCar.Brand + " " + myCar.ModelName);
myCar.Start();
}
}How it works
Vehicleis the base class.Car : Vehiclemeans Car inherits from Vehicle.- Car object gets
BrandandStart()from Vehicle.
You should see
Ford Mustang Vehicle started