C# Inheritance
Inheritance is an important aspect of object-oriented programming (OOP) that allows you to define a new class based on an existing one. In C#, you can use inheritance to derive a new class from an existing one and add new functionality or behavior as needed. In this tutorial, we'll discuss how to use inheritance in C#.
Syntax
The syntax for defining a class that derives from an existing class in C# is as follows:
class MyClass : MyBaseClass {
// class members
}
You use the ":" symbol to indicate that you're deriving a new class from an existing class.
Example
Let's say we want to define a class called "Rectangle" that has a width and height property and a method that calculates its area. We can define a base class called "Shape" that has a virtual method called "CalculateArea" and then derive the "Rectangle" class from it:
class Shape {
public virtual double CalculateArea() {
return 0;
}
}
class Rectangle : Shape {
public double Width { get; set; }
public double Height { get; set; }
public override double CalculateArea() {
return Width * Height;
}
}
Now, we can use the Rectangle class in our code:
Rectangle rectangle = new Rectangle { Width = 5, Height = 10 };
double area = rectangle.CalculateArea();
Console.WriteLine(area); // Output: 50
Output
When we run the example code above, the output will be:
50
This is because we created a new Rectangle object and set its Width and Height properties, then called its CalculateArea method, which returned the area (Width * Height).
Explanation
In the example above, we defined a base class called "Shape" that has a virtual method called "CalculateArea". We then defined a derived class called "Rectangle", which inherits from the "Shape" class and overrides the "CalculateArea" method to provide its own implementation.
When we created a new Rectangle object and set its Width and Height properties, we were able to call its CalculateArea method and get the area of the rectangle.
Use
Inheritance is useful when you want to create a new class that shares properties and behavior with an existing class but adds additional functionality or behavior. This allows you to reuse code and create classes that are easier to maintain.
Important Points
- Inheritance allows you to create new classes based on existing ones.
- You use the ":" symbol to indicate that a class derives from an existing class.
- Inheritance allows you to reuse code and create classes that are easier to maintain.
Summary
In this tutorial, we discussed how to use inheritance in C#. We covered the syntax, example, output, explanation, use, and important points of inheritance in C#. With this knowledge, you can now use inheritance in your C# code to create new classes based on existing ones and add additional functionality or behavior as needed.