Member-only story
C# Inheritance with Examples
3 min readApr 21, 2024
You can create a base class (parent class). You can derive a new class (child class) from this existing base class (parent class). When you inherit a child class with base class you also inherit it’s members (fields, methods, properties etc.). you can also add these members and also can modify them as needed.
Declare and Use Inheritance:
Here’s how you declare and use Inheritance in C#:
Example
// base class(parent class)
public class Fruit
{
public void Name()
{
Console.WriteLine("Fruit has name.");
}
public void Eat()
{
Console.WriteLine("Fruit is for eating.");
}
public void Taste()
{
Console.WriteLine("Fruit has taste.");
}
public void Color()
{
Console.WriteLine("Fruit has color.");
}
}
// derived class (child class)
public class WaterMelon : Fruit
{
public void hasWater()
{
Console.WriteLine("WaterMelon has 92% water.");
}
public void hasTaste()
{
Console.WriteLine("WaterMelon has mixture of sweet, sour and bitter taste.");
}
public void hasColor()
{
Console.WriteLine("WaterMelon has red green color");
}
}
In this example:
Fruit is the base class, and it has a property Name and a method getName.