C# inheritance
In C#, inheritance is a mechanism that allows you to create a new class from an existing class, inheriting all of its properties and methods. The new class is called the "derived" class, and the existing class is called the "base" class. Inheritance is a fundamental concept in object-oriented programming, and it helps you to create complex class hierarchies that are easy to understand and maintain.
To create a derived class in C#, you use the :
operator to specify the base class, like this:
class DerivedClass : BaseClass { // Derived class members go here }
The DerivedClass
is the new class that you are creating, and BaseClass
is the class that you are inheriting from. The members of the base class are automatically inherited by the derived class, and you can access them using the base
keyword. You can also add new members to the derived class, including properties, fields, methods, and events.
Here's an example that demonstrates how to create a derived class in C#:
class Shape { protected double width; protected double height; public void SetWidth(double w) { width = w; } public void SetHeight(double h) { height = h; } } class Rectangle : Shape { public double GetArea() { return width * height; } }
In this example, the Shape
class is the base class, and the Rectangle
class is the derived class. The Rectangle
class inherits the width
and height
fields and the SetWidth
and SetHeight
methods from the Shape
class, and it defines a new GetArea
method that calculates the area of the rectangle.
You can create an instance of the Rectangle
class and use its methods like this:
Rectangle rect = new Rectangle(); rect.SetWidth(5); rect.SetHeight(10); double area = rect.GetArea();
In this example, you create a new instance of the Rectangle
class, set its width and height, and calculate its area using the GetArea
method. The GetArea
method uses the width
and height
fields inherited from the Shape
class to perform the calculation.
Inheritance is a powerful mechanism that allows you to reuse code and create complex class hierarchies in C#. By using inheritance, you can create new classes that are tailored to your specific needs, while still benefiting from the functionality and features of the base class.