In C# programming, inheritance involves an object gaining all attributes and behaviors from its parent object automatically. This allows for the reusability, extension, or modification of properties and behaviors defined in a different class.
In C# programming language, the derived class refers to the class that acquires the members of another class, known as the base class. The derived class is a specialized version of the base class, inheriting its properties and functionalities.
Syntax
It has the following syntax:
class BaseClass
{
// base class members
}
class DerivedClass : BaseClass
{
// derived class members
}
In this format;
- Subclass: This refers to a class that derives from another class, known as a base class. It has the ability to include additional fields and methods from the base class.
- Parent Class: Also referred to as the base class, it is the class that passes on its characteristics to another class.
C# Inheritance Example
Let's consider a scenario to demonstrate the concept of inheritance in C#.
Example
using System;
public class Animal //base class
{
public void eat() {
Console.WriteLine("Eating...");
}
}
public class Dog: Animal //derived class
{
public void bark() {
Console.WriteLine("Barking...");
}
}
class TestInheritance2{
public static void Main(string[] args)
{
Dog d1 = new Dog();
d1.eat();
d1.bark();
}
}
Output:
Eating...
Barking...
Explanation:
In this illustration, we start with a base class Animal that contains a function eat. The subclass Dog is derived from Animal and introduces its own function bark. Within the main function, an instance of Dog is instantiated, allowing access to both eat and bark methods. The program concludes by displaying the result.
Types of Inheritance
There exist various forms of inheritance within the C# programming language. These include:
The <style> section includes a CSS class for a placeholder diagram. This diagram has a background styled with a linear gradient from #374151 to #1f2937, a border-radius of 12px, padding of 40px, margin of 20px on the top and bottom, and text aligned to the center. Inside the placeholder diagram, there are elements for the placeholder icon with a font size of 3rem and a margin-bottom of 10px, as well as text for the placeholder with a color of #9ca3af and a font size of 1rem. This setup is designed for creating visually appealing and informative diagrams in web development projects.
Now, we will explore each of these inheritances individually.
Single Inheritance in C#
In C# programming, single inheritance is when a subclass inherits from a single superclass.
The <style> component is styled with a linear gradient background, rounded borders, and centered text. It includes an icon with a font size of 3rem and text with a font size of 1rem. </style>
Single Inheritance Example
Let's consider an instance of single inheritance in C#.
Example
using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
class SingleInheritance{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
}
}
Output:
Salary: 40000
Bonus: 10000
Explanation:
In this instance, we start with a base class called Employee, with Programmer being its subclass. Subsequently, the Programmer class acquires the salary attribute from the Employee class. Additionally, it introduces its own attribute, bonus. Upon instantiation of a Programmer object, we gain access to both the Salary and bonus attributes.
Multi-Level Inheritance
In C# programming, multi-level inheritance occurs when a class inherits from another class, which in turn is inherited by a third class. This transitive process ensures that the final derived class inherits all the properties and methods from its base classes.
The <style> CSS class defines the styling for a placeholder diagram, including a gradient background, border radius, padding, margin, and center-aligned text. Inside the diagram, there is a placeholder icon with a size of 3rem and a margin-bottom of 10px. Additionally, the placeholder text color is #9ca3af with a font size of 1rem.
Let's consider three classes, such as Class A, Class B, and Class C, where Class A represents the base class, Class B represents the intermediary class, and Class C represents the derived class. It shows that one class inherits another class, which is further inherited by another class.
Syntax:
It has the following syntax:
class Base
{
// body of Base class
};
class Intermediate : public Base
{
//Body of intermediate class
};
class Derived : public Intermediate
{
// Body of derived class
};
Multi-Level Inheritance Example
Let's consider a scenario to demonstrate the concept of multi-level inheritance in C#.
Example
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal
{
public void bark() { Console.WriteLine("Barking..."); }
}
public class BabyDog : Dog
{
public void weep() { Console.WriteLine("Weeping..."); }
}
class Mul_level_inheritance{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}
Output:
Eating...
Barking...
Weeping...
Explanation:
In this instance, we are examining a Dog class that extends Animal, with the BabyDog class extending Dog. Consequently, a BabyDog object is able to utilize functions from all three classes: eat, bark, and weep.
Hierarchical Inheritance
In C# programming, hierarchical inheritance refers to the scenario where multiple derived classes inherit from a single base class. This type of inheritance allows the base class to encompass shared characteristics among its child classes.
The <style> element defines the styling for a placeholder diagram. This includes setting a background color gradient, border radius, padding, margin, and text alignment within the diagram. Additionally, it specifies the styles for the icon and text displayed within the placeholder diagram. The icon size, margin, and text color and size are all customized within this element. The purpose of this element is to create visually appealing and informative placeholder diagrams on a web page. </style>
Syntax:
It has the following syntax:
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
C# Hierarchical Inheritance Example
Let's consider a scenario to demonstrate the concept of Hierarchical inheritance in C#.
Example
using System;
class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle has started");
}
}
class Car : Vehicle
{
public void Drive()
{
Console.WriteLine("Driving the car");
}
}
class Bike : Vehicle
{
public void Ride()
{
Console.WriteLine("Riding the bike");
}
}
class Program
{
static void Main()
{
Car car = new Car();
car.Start();
car.Drive();
Bike bike = new Bike();
bike.Start();
bike.Ride();
}
}
Output:
Vehicle has started
Driving the car
Vehicle has started
Riding the bike
Explanation:
In this illustration, we start with a foundational class known as Vehicle containing a method called Start. Subsequently, we introduce two subclasses - Car and Bike, each equipped with distinct methods Drive and Ride. Within the Main function, we instantiate objects of both Car and Bike. These objects make use of the redefined Start method along with their specific class methods, showcasing the concept of hierarchical inheritance.
Multiple Inheritance
In C#, multiple inheritance refers to a scenario where a class inherits from multiple interfaces, as opposed to inheriting from multiple base classes which is not supported in C#. Instead, utilizing interfaces allows for achieving multiple inheritance in C#.
The <style> element is styled with a linear gradient background, border radius of 12px, padding of 40px, margin of 20px top and bottom, and centered text alignment. Within this element, there is an icon with a font size of 3rem and a margin-bottom of 10px. Additionally, there is text styled with a color of #9ca3af and a font size of 1rem.
Syntax:
It has the following syntax:
interface A
{
void Method1();
}
interface B
{
void Method2();
}
class MyClass : A, B
{
public void Method1() { }
public void Method2() { }
}
C# Multiple Inheritance Example
Let's consider an instance to demonstrate the concept of multiple inheritance in C#.
Example
using System;
interface IWriter
{
void Write();
}
interface IReader
{
void Read();
}
class Document : IWriter, IReader
{
public void Write()
{
Console.WriteLine("Writing to the document.");
}
public void Read()
{
Console.WriteLine("Reading from the document.");
}
}
class Program
{
static void Main()
{
Document doc = new Document();
doc.Read();
doc.Write();
}
}
Output:
Reading from the document.
Writing to the document.
Explanation:
In this instance, we consider two interfaces, IWriter and IReader, each specifying the Write and Read methods. The class Document extends both interfaces, thereby offering implementations for both functions. Within the Main method, an instance of a document is instantiated and utilized to invoke the Read and Write functions. This showcases the capability of C# to enable a class to inherit behavior from multiple sources through interfaces, despite not supporting direct multiple class inheritance.
Hybrid Inheritance
The C# coding language does not have built-in support for multiple inheritance through classes in order to avoid ambiguity. Hybrid inheritance combines multilevel inheritance with hierarchical inheritance.
The <style> element defines a CSS class for creating diagrams. This class includes styling properties such as background color, border radius, padding, margin, and text alignment. Within the diagram, there is an icon element with a specific font size and margin, as well as text content styled with a defined color and font size.
Syntax:
It has the following syntax:
// Base class
class BaseClass
{
public void DisplayBase() { }
}
// Interface 1
interface A
{
void Method1();
}
// Interface 2
interface B
{
void Method2();
}
// Derived class inherits from BaseClass and implements multiple interfaces
class DerivedClass : BaseClass, A, B
{
public void Method1() { }
public void Method2() { }
}
C# Hybrid Inheritance Example
Let's consider a scenario to demonstrate the concept of Hybrid Inheritance in C#.
Example
using System;
interface Employee
{
void Work();
}
class Person
{
public void ShowDetails()
{
Console.WriteLine("Person details displayed");
}
}
class Manager : Person, Employee
{
public void ManageTeam()
{
Console.WriteLine("Managing the team");
}
public void Work()
{
Console.WriteLine("Manager is working");
}
}
class Developer : Person, Employee
{
public void WriteCode()
{
Console.WriteLine("Writing code");
}
public void Work()
{
Console.WriteLine("Developer is working");
}
}
class Program
{
static void Main()
{
Manager m = new Manager();
m.ShowDetails();
m.ManageTeam();
m.Work();
Developer d = new Developer();
d.ShowDetails();
d.WriteCode();
d.Work();
}
}
Output:
Person details displayed
Managing the team
Manager is working
Person details displayed
Writing code
Developer is working
Explanation:
In this instance, we consider a base class named Person, from which the class Student derives, and subsequently, the class CollegeStudent inherits from Student. CollegeStudent then incorporates the interface IExaminable. Within the main function, an instance of CollegeStudent invokes functions from Person, Student, its own functions, and the interface function, showcasing a combination of inheritance involving both classes and interfaces.
Access Modifiers in C# Inheritance
In C# programming, access modifiers play a crucial role in managing the visibility of class members during inheritance. C# inheritance involves five primary types of access modifiers, which include:
1) Public Access Modifiers
In C#, the public access modifier is primarily utilized to indicate that base class elements are accessible within the class, derived class, and externally. This modifier is also included in the derived class instance and allows data to be accessed beyond the declared scope.
2) Private Access Modifiers
Access to private members within the base class is exclusive to that class, while the accessibility of these members is confined within the derived classes.
3) Protected Access Modifiers
Protected members of the base class are accessible within the same class and in its derived classes. However, they remain inaccessible outside the class hierarchy when it comes to inheritance.
4) Internal Access Modifiers
The internal members can be accessed in the same assembly. It cannot be accessed outside the class. The internal keyword is used to define the internal access modifier in C#. It is useful in large applications with multiple files.
5) Protected Internal Access Modifiers
Protected internal members are accessible within the declaring assembly, similar to internal members. They can also be accessed by derived classes, akin to protected members. The protected internal access modifier is employed to define this combination of access levels.
Method Overriding in C# Inheritance
In C# inheritance, method overriding allows a subclass to provide a unique implementation for a method that is already declared in the superclass. When a method with the same signature exists in both the superclass and the subclass, the subclass method takes precedence over the superclass method.
Method Overriding Example in C# Inheritance
Let's consider an example to demonstrate Method overriding within C# inheritance.
Example
using System;
class Student // Base class
{
public string Name;
public int RollNo;
public Student(string std_name, int std_rollNo)
{
Name = std_name;
RollNo = std_rollNo;
}
// Virtual method
public virtual void ShowInfo()
{
Console.WriteLine($"Student: {Name}, Roll No: {RollNo}");
}
}
class CollegeStudent : Student // Derived class
{
public string Course;
public CollegeStudent(string std_name, int std_rollNo, string std_course)
: base(std_name, std_rollNo)
{
Course = std_course;
}
// Overriding the base method
public override void ShowInfo()
{
Console.WriteLine($"College Student: {Name}, Roll No: {RollNo}, Course: {Course}");
}
}
class SchoolStudent : Student // Another derived class
{
public int ClassGrade;
public SchoolStudent(string std_name, int std_rollNo, int std_grade)
: base(std_name, std_rollNo)
{
ClassGrade = std_grade;
}
// Overriding the base method
public override void ShowInfo()
{
Console.WriteLine($"School Student: {Name}, Roll No: {RollNo}, Grade: {ClassGrade}");
}
}
class Program
{
static void Main()
{
Student s1 = new CollegeStudent("Michael", 101, "Computer Science");
Student s2 = new SchoolStudent("Richard", 202, 10);
// Calls overridden methods
s1.ShowInfo();
s2.ShowInfo();
}
}
Output:
College Student: Michael, Roll No: 101, Course: Computer Science
School Student: Richard, Roll No: 202, Grade: 10
Explanation:
In this instance, we illustrate the concept of method overriding within C# inheritance. In this scenario, we present a class centered around students, which includes a virtual method named ShowInfo. This method is redefined in the subclasses CollegeStudent and SchoolStudent to provide additional and specialized information. Upon instantiation of objects using references from the base class, the overridden methods within the derived classes are invoked.
Type Conversion in C# Inheritance
In C# inheritance, the concept of type conversion involves transforming an object from a base class to its derived class, or vice versa. Implicitly, a derived class object can be viewed as a base class object (upcasting), whereas converting a base class object to a derived class object necessitates explicit casting (downcasting). This mechanism is particularly beneficial when managing derived objects through base class references.
Type Conversion Example in C# Inheritance
Let's consider an example to demonstrate type conversion within C# inheritance.
Example
using System;
class Animal //base class
{
public void Speak()
{
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog barks");
}
}
class Program
{
static void Main()
{
// Upcasting
Animal a = new Dog();
a.Speak();
// Downcasting
if (a is Dog)
{
Dog d = (Dog)a;
d.Bark();
// Downcasting using 'as'
Dog d2 = a as Dog;
if (d2 != null)
{
d2.Bark();
}
}
}
}
Output:
Animal speaks
Dog barks
Dog barks
Explanation:
In this example, we have taken a Person class that defines a constructor and a virtual method ShowInfo. The derived class Employee inherits from Person, which calls the base class constructor using the base(emp_name) method, and overrides ShowInfo while also calling the base method using the base.ShowInfo method. It ensures that both the base class information (Name) and the derived class information (EmpID) are displayed together.
Base Keyword in C# Inheritance
In C# programming, the base keyword plays a crucial role within a subclass to reach the members of the superclass. It is employed to invoke the superclass constructor within the subclass constructor. Additionally, it enables the subclass to interact with the superclass methods, properties, and fields that have been concealed or redefined in the subclass.
Syntax:
It has the following syntax:
base.MemberName
base (...)
In this format,
- MemberName: This assists in retrieving the members of the base class.
- base (…): It invokes the base class constructor from the constructor of the derived class.
Base Keyword Example in C# Inheritance
Let's consider an example to demonstrate the fundamental keyword in C# inheritance.
Example
using System;
class Person // Base class
{
public string Name;
public Person(string emp_name)
{
Name = emp_name;
}
public virtual void ShowInfo()
{
Console.WriteLine($"Employee Name: {Name}");
}
}
class Employee : Person // Derived class
{
public int EmpID;
// Calling base constructor
public Employee(string emp_name, int emp_id) : base(emp_name)
{
EmpID = emp_id;
}
// Overriding method
public override void ShowInfo()
{
// Calling base class method using base keyword
base.ShowInfo();
Console.WriteLine($"Employee ID: {EmpID}");
}
}
class Program
{
static void Main()
{
Employee emp = new Employee("Johnson", 201);
emp.ShowInfo();
}
}
Output:
Employee Name: Johnson
Employee ID: 201
Explanation:
In this illustration, we start with a superclass named Person that contains a constructor and a virtual function named ShowInfo. Subsequently, we introduce a subclass called Employee that extends Person, invoking the superclass constructor via the base keyword, and redefines the ShowInfo function. To display information from both the superclass and the subclass simultaneously, we utilize the base.ShowInfo method.
Advantages of Inheritance in C#
There are several advantages of inheritance in C#. Some of them are as follows:
- Inheritance allows us to reuse the methods and properties of a base class in the derived class, which helps to reduce code duplication.
- It allows method overriding, which allows us to use different classes to provide specific implementations while sharing the same interface.
- It makes a hierarchical class structure, which helps to make the code more structured and easier to understand.
- If we make some changes in the base class, it is automatically applied in all derived classes.
Disadvantages of Inheritance in C#
There are several disadvantages of inheritance in C#. Some of them are as follows:
- In C# inheritance, derived classes are tightly coupled with the base class because they inherit methods and properties of the base class. If we make any change in the base class, it may affect all the derived classes.
- It can increase the code complexity by introducing additional abstraction levels.
- If we create dependencies between the base class and the derived class, inheritance may make the code weaker.
- Deep inheritance hierarchies may make the code harder to understand, debug, and maintain.
Conclusion
In summary, C# inheritance plays a vital role in object-oriented programming as it allows a class to acquire the attributes and functionalities of another class. In C#, the derived class is the one that inherits the properties of another class, while the base class is the one whose properties are inherited. This concept supports the reuse of code, the ability to extend functionality, and the implementation of polymorphism, ultimately enhancing the maintainability and organization of applications.
C# Inheritance FAQs
In C# programming, inheritance is a mechanism where a new class (derived class) is created by inheriting attributes and behaviors from an existing class (base class). This enables the derived class to reuse the code of the base class and also add new features or modify existing ones.
In C#, inheritance is a fundamental feature of object-oriented programming that enables a class to acquire behaviors and attributes from another class. This mechanism promotes code reusability and facilitates the organization of classes in hierarchical structures.
2) How do we use inheritance in C#?
We utilize the colon (:) symbol to indicate inheritance in C#.
class BaseClass { }
class DerivedClass: BaseClass { }
Here, DerivedClass inherits from BaseClass.
3) What are the primary benefits of utilizing inheritance in C#?
Several advantages of inheritance in C# are as follows:
- It avoids duplication by sharing code.
- It allows us to extend or modify the behavior of base classes.
- It makes program design more logical and maintainable.
The primary distinction between an abstract class and an interface in terms of C# inheritance lies in their implementation.
The primary distinction between an abstract class and an interface lies in the fact that an abstract class is capable of containing implementations, constructors, and fields. In contrast, an interface is restricted from incorporating implementations (except for default implementations in more recent editions of C#), constructors, or fields, serving only for contract declaration.
The base keyword in the C# programming language is utilized to access members of the base class from within a derived class.
In C# programming, the base keyword allows us to access members of the base type within a derived type, specifically constructors and overridden methods.