Inheritance is an important concept in object-oriented programming, and C# supports it through the use of classes. Inheritance allows you to create a new class that is a modified version of an existing class. The new class is called the derived class, and the existing class is the base class.
The derived class inherits the members of the base class, which means it has access to the base class’s methods, properties, and fields. The derived class can also have its own members, which means it can extend the functionality of the base class.
Here is an example of how you can use inheritance in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | using System; namespace InheritanceExample { // Base class public class Shape { public double Width { get; set; } public double Height { get; set; } public virtual double Area() { return Width * Height; } } // Derived class public class Rectangle : Shape { public override double Area() { return Width * Height; } } // Derived class public class Triangle : Shape { public override double Area() { return (Width * Height) / 2; } } class Program { static void Main(string[] args) { Rectangle rectangle = new Rectangle(); rectangle.Width = 10; rectangle.Height = 20; Console.WriteLine("Rectangle Area: " + rectangle.Area()); Triangle triangle = new Triangle(); triangle.Width = 10; triangle.Height = 20; Console.WriteLine("Triangle Area: " + triangle.Area()); } } } |
In this example, the Shape
class is the base class, and the Rectangle
and Triangle
classes are derived classes. The Rectangle
and Triangle
classes override the Area
method of the base class to provide their own implementation.
When you run this code, it will output the following:
1 2 3 4 | Rectangle Area: 200 Triangle Area: 100 |