.NET HELP

C# Inheritance (How It Works For Developers)

Published March 6, 2024
Share:

Introduction

One of the main characteristics of C#, Inheritance, is well known for its strong support of Object-Oriented Programming (OOP) principles. It is essential for writing scalable and effective code. This post will explore the topic of C# inheritance with an emphasis on real-world uses for IronPDF library, a potent library that makes handling PDFs in C# programs easier.

How to Use C# Inheritance

  1. Create a new C# console project
  2. Create a base class with some methods.
  3. Write a new derived class and inherit a class.
  4. Call the function/Method that is available in a base class.
  5. Process the operation and Dispose of the object.

Inheritance in C#: An Overview

A key idea in object-oriented programming (OOP) is inheritance, which lets a class (the derived or subclass) take on traits and characteristics from another class (the base or superclass). In C#, inheritance is accomplished by putting the base class name after the: (colon) symbol.

Single Inheritance

A class can inherit from just one base class in C# since a single inheritance is supported. When you want a derived class to increase the capability of a single base class, you utilize the most basic type of inheritance: compound inheritance.

class Animal { /* Base/ Parent class */ }
class Dog : Animal { /* Derived class */ }
class Animal { /* Base/ Parent class */ }
class Dog : Animal { /* Derived class */ }
Friend Class Animal
End Class
Friend Class Dog
	Inherits Animal

End Class
VB   C#

Hierarchical Inheritance

Several classes that share a base class are inherited by them in a hierarchical inheritance scheme. Which is a single-based class inherited by multiple derived classes. There could be further characteristics unique to each derived class depending on its purpose.

class Animal { /* Base class */ }
class Dog : Animal { /* Derived class */ }
class Wolf : Animal { /* Derived class */ }
class Animal { /* Base class */ }
class Dog : Animal { /* Derived class */ }
class Wolf : Animal { /* Derived class */ }
Friend Class Animal
End Class
Friend Class Dog
	Inherits Animal

End Class
Friend Class Wolf
	Inherits Animal

End Class
VB   C#

Multilevel Inheritance

A class functions as both a base class and a derived class in multilevel inheritance. As a result, a chain of inheritance is formed, with each class expanding on the characteristics of its predecessor.

class Animal { /* Base class */ }
class Mammal : Animal { /* Derived class */ }
class Dog : Mammal { /* Derived class  */ }
class Animal { /* Base class */ }
class Mammal : Animal { /* Derived class */ }
class Dog : Mammal { /* Derived class  */ }
Friend Class Animal
End Class
Friend Class Mammal
	Inherits Animal

End Class
Friend Class Dog
	Inherits Mammal

End Class
VB   C#

Interface Inheritance

A class in C# can implement one or more interfaces and inherit from a single base class. This allows a class to inherit the implementation of methods described in interfaces, thus achieving a type of multiple inheritance.

interface ILogger
{
    void Log(string message);
}
class ConsoleLogger : ILogger //child class
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}
class FileLogger : ILogger
{
    public void Log(string message)
    {
        // Log to file
    }
}
interface ILogger
{
    void Log(string message);
}
class ConsoleLogger : ILogger //child class
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}
class FileLogger : ILogger
{
    public void Log(string message)
    {
        // Log to file
    }
}
Friend Interface ILogger
	Sub Log(ByVal message As String)
End Interface
Friend Class ConsoleLogger 'child class
	Implements ILogger

	Public Sub Log(ByVal message As String) Implements ILogger.Log
		Console.WriteLine(message)
	End Sub
End Class
Friend Class FileLogger
	Implements ILogger

	Public Sub Log(ByVal message As String) Implements ILogger.Log
		' Log to file
	End Sub
End Class
VB   C#

Abstract Classes and Methods

In C#, an abstract class serves as a base class for other classes and is incapable of being created on its own. An abstract class's job is to give its derived classes a shared interface and set of functions. It acts as a model or template that outlines the attributes and methods that its descendant classes need to implement. Interfaces are a functionality offered by C#. A type of multiple inheritance is essentially made possible via interfaces, which let a class implement numerous contracts.

One or more abstract methods can be defined for a base class using abstract classes. Subsequently, these abstract methods must have concrete implementations provided by derived classes.

abstract class Shape
{
    public abstract double Area(); // Abstract method
}
class Square : Shape
{
    public double Radius { get; set; }
    public override double Area()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }
}
abstract class Shape
{
    public abstract double Area(); // Abstract method
}
class Square : Shape
{
    public double Radius { get; set; }
    public override double Area()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }
}
Friend MustInherit Class Shape
	Public MustOverride Function Area() As Double ' Abstract method
End Class
Friend Class Square
	Inherits Shape

	Public Property Radius() As Double
	Public Overrides Function Area() As Double
		Return Math.PI * Math.Pow(Radius, 2)
	End Function
End Class
VB   C#

These are only a few applications of inheritance in C#. The intended degree of flexibility in the codebase, the connections between classes, and the design goals all influence the method that is chosen.

IronPDF

The .NET library IronPDF allows programmers to create, edit, and alter PDF documents using the C# language. A variety of tools and capabilities are provided by the IronPDF library to enable various tasks with PDF files, such as generating PDFs from HTML, converting HTML to PDF, merging or splitting PDF documents, and adding text, images, and annotations to existing PDFs. To know more about IronPDF, please refer to the IronPDF documentation.

Install IronPDF

Acquire the IronPDF library; the upcoming patch requires it. To do this, enter the following code into the Package Manager:

Install-Package IronPDF 
//or 
dotnet add package IronPdf

C# Inheritance (How It Works For Developers): Figure 1 - Install IronPDF package using Package Manager Console and enter the following commands: "Install-Package IronPDF" or "dotnet add package IronPdf".

Another option is to look for the package "IronPDF" using the NuGet Package Manager. Among all the NuGet packages related to IronPDF, we may select and download the required package from this list.

C# Inheritance (How It Works For Developers): Figure 2 - You can also install the IronPDF package using NuGet Package Manager. Search for the package "ironpdf" in the Browse tab, then select and install the latest version of the IronPDF.

IronPDF in Inherited Classes

A feature-rich library called IronPDF was created to make working with PDF documents in C# easier. By integrating IronPDF with inherited classes, you may improve the functionality of your application and create, manipulate, and more PDFs with ease.

The Advantages of Inheritance with IronPDF

  • Organized Code Organisation: By establishing a class hierarchy, inheritance helps to foster an organized code organization. You can create classes specifically for handling PDFs with IronPDF integration and still have a clean, well-organized codebase.
  • Reusing Code: Classes that inherit from their base classes allow for the reuse of code. This is especially useful if you are using a library such as IronPDF since it allows you to encapsulate common PDF-related functions into a base class that you can reuse in other areas of your application.

To expand the capabilities of PdfDocument, particularly for IronPDF integration, let's build a class named IronPdfDocument:

using IronPdf;
public class IronPdfDocument : PdfDocument
{
    // Additional properties or methods specific to IronPDF can be added here
    public void ConvertToPdf()
    {
        // Code to convert the HTML to PDF using IronPDF
           var Renderer = new IronPdf.HtmlToPdf();
           var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>");
           PDF.SaveAs("Output.pdf");
    }
}
using IronPdf;
public class IronPdfDocument : PdfDocument
{
    // Additional properties or methods specific to IronPDF can be added here
    public void ConvertToPdf()
    {
        // Code to convert the HTML to PDF using IronPDF
           var Renderer = new IronPdf.HtmlToPdf();
           var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>");
           PDF.SaveAs("Output.pdf");
    }
}
Imports IronPdf
Public Class IronPdfDocument
	Inherits PdfDocument

	' Additional properties or methods specific to IronPDF can be added here
	Public Sub ConvertToPdf()
		' Code to convert the HTML to PDF using IronPDF
		   Dim Renderer = New IronPdf.HtmlToPdf()
		   Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>")
		   PDF.SaveAs("Output.pdf")
	End Sub
End Class
VB   C#

IronPdfDocument is an enhanced example that derives from PdfDocument. This class is designed to operate with IronPDF easily; you may use certain attributes or methods to handle PDF-related functionality with ease. To know more about IronPDF features, refer to the IronPDF features page.

Building a PDF Report Generator

Let's put these ideas into practice by utilizing inheritance and IronPDF to create a basic PDF report generator. First, we'll work with the Report base class:

public class Report
{
    public virtual void GenerateReport()
    {
                var Renderer = new IronPdf.HtmlToPdf();
                var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>");
                PDF.SaveAs("Output.pdf");
    }
}
public class Report
{
    public virtual void GenerateReport()
    {
                var Renderer = new IronPdf.HtmlToPdf();
                var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>");
                PDF.SaveAs("Output.pdf");
    }
}
Public Class Report
	Public Overridable Sub GenerateReport()
				Dim Renderer = New IronPdf.HtmlToPdf()
				Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>")
				PDF.SaveAs("Output.pdf")
	End Sub
End Class
VB   C#

Let's now construct PdfReport, a derived class that adds IronPDF features and inherits from the base class:

public class PdfReport : Report
{
    public override void GenerateReport()
    {
        var Renderer = new IronPdf.HtmlToPdf();
        var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF</h1>");
        PDF.SaveAs("Output.pdf");
        Console.WriteLine("Generating PDF report...");
        // Additional code specific to PDF generation using IronPDF
    }
}
public class PdfReport : Report
{
    public override void GenerateReport()
    {
        var Renderer = new IronPdf.HtmlToPdf();
        var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF</h1>");
        PDF.SaveAs("Output.pdf");
        Console.WriteLine("Generating PDF report...");
        // Additional code specific to PDF generation using IronPDF
    }
}
Public Class PdfReport
	Inherits Report

	Public Overrides Sub GenerateReport()
		Dim Renderer = New IronPdf.HtmlToPdf()
		Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF</h1>")
		PDF.SaveAs("Output.pdf")
		Console.WriteLine("Generating PDF report...")
		' Additional code specific to PDF generation using IronPDF
	End Sub
End Class
VB   C#

The above example shows that The Title property and the GenerateReport function are inherited by PdfReport from the existing class which is the base class Report in this example. It adds a new property called Author and overrides the GenerateReport function with custom logic for IronPDF-based PDF report generation. Below is the output PDF generated from the code.

C# Inheritance (How It Works For Developers): Figure 3

To learn about the code to convert an HTML string to PDF, refer to the HTML to PDF example.

Conclusion

When paired with libraries like IronPDF, inheritance is a powerful feature that enhances the application development process. The foundations of inheritance have been covered in this post, along with a useful how-to for integrating the idea with IronPDF.

The development of hierarchical class structures results in a modular and well-structured codebase. When you develop classes that inherit the broad capabilities of their base classes but cater to specific tasks, the advantages of code extension and reusability become clear. These benefits are increased when IronPDF is integrated, offering a seamless solution for managing PDF documents in your C# applications.

IronPDF's $749 Light pack incorporates a super durable permit, redesign choices, and an extended period of programming support. During the watermarked trial period, clients can evaluate the product in genuine application settings. To learn more about IronPDF's pricing, licensing, and trial version, please visit the IronPDF licensing page. Visit the official Iron Software website to become familiar with other Iron Software products.

< PREVIOUS
C# Linter (How It Works For Developers)
NEXT >
C# Random Int (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >