C# Inheritance
An object acquires all the properties and behaviors of its parent object automatically by using the process of inheritance in C#. It is useful when required to reuse, extend or modify the attributes and behaviors defined in a different class. The derived class in C# is the class that inherits the members of another class and is the specialized class for the base class. The base class is the class whose members are inherited.
Advantage:
C# inheritance provides the advantage of code reusability since the members of the parent class can be reused. Also, less code is required in the class because there is no need to define the member again.
Single Level Inheritance:
In C# in the single-level inheritance one class inherits another class.
Example 1:
using System; public class Student { public float marks = 90; } public class Topper: Student { public float extra = 5; } class Std{ public static void Main(string[] args) { Topper t1 = new Topper(); Console.WriteLine("Marks: " + t1.marks); Console.WriteLine("Extra Marks: " + t1.extra); } } |
Output:
Explanation:
In the above example, we are displaying the use and behavior of the single-level inheritance in C# which inherits the fields only. Here, Student is the base class and the Topper is the derived class.
Example 2:
using System; public class Flower { public void color() { Console.WriteLine("Red Flower!!"); } } public class Lily: Flower { public void white() { Console.WriteLine("White Lily!!"); } } class flwr{ public static void Main(string[] args) { Lily l1 = new Lily(); l1.color(); l1.white(); } } |
Output:
Explanation:
In the above example, we are displaying the use and behavior of the single-level inheritance in C# which inherits the methods only.
C# Multi-Level Inheritance:
In C#, in the multi-level inheritance one class inherits another class which is further inherited by another class. All the members of the base classes will be acquired by the last derived class because the inheritance is transitive.
Example:
using System; public class Flower { public void color() { Console.WriteLine("Red Flower!!"); } } public class Lily: Flower { public void white() { Console.WriteLine("White Lily!!"); } } public class WhiteLily : Lily { public void beauty() { Console.WriteLine("Beautiful!!"); } } class flwr{ public static void Main(string[] args) { WhiteLily l1 = new WhiteLily(); l1.color(); l1.white(); l1.beauty(); } } |
Output:
Explanation:
In the above example, we are displaying the use and behavior of the multi-level inheritance in C#.