C# Single Inheritance

In object-oriented programming, inheritance is the process by which one class acquires the properties and methods of another class. This can save time and effort in coding, as well as promote code reusability.

Single inheritance is a type of inheritance in which a class is derived from only one base class. In this article, we will discuss the concept of single inheritance in C# with examples.

Syntax for Single Inheritance

The syntax for single inheritance in C# is as follows:

1class DerivedClass : BaseClass 2{ 3 // Derived class members 4}

In this syntax, DerivedClass is the derived class or subclass, and BaseClass is the base class or superclass.

Example of Single Inheritance

1using System; 2 3//Base class 4public class Person 5{ 6 public string FirstName; 7 public string LastName; 8 9 public void Display() 10 { 11 Console.WriteLine("First Name: " + FirstName); 12 Console.WriteLine("Last Name: " + LastName); 13 } 14} 15 16//Derived class 17public class Employee : Person 18{ 19 public string CompanyName; 20 public void DisplayCompanyName() 21 { 22 Console.WriteLine("Company Name: " + CompanyName); 23 } 24} 25 26class Program 27{ 28 static void Main(string[] args) 29 { 30 //Creating object of derived class 31 Employee emp = new Employee(); 32 33 //Setting values 34 emp.FirstName = "William"; 35 emp.LastName = "Max"; 36 emp.CompanyName = "123 Corporation"; 37 38 //Calling the methods 39 emp.Display(); 40 emp.DisplayCompanyName(); 41 } 42}

In the example above, we have a base class Person and a derived class Employee. The Employee class inherits the properties and methods of the Person class. The Employee class also has an additional property CompanyName and a method DisplayCompanyName(). We create an object of the Employee class and set its properties. We then call the methods of both the Person and Employee classes using the object of the Employee class.