Skip to footer content
.NET HELP

C# Inheritance (How It Works For Developers)

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 emphasizing 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 from the base class.
  4. Call the function/method that is available in the 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

In C#, a class can inherit from just one base class since only single inheritance is supported. This is useful when you want a derived class to extend the capabilities of a single base class.

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
$vbLabelText   $csharpLabel

Hierarchical Inheritance

Several classes can inherit from the same base class in a hierarchical inheritance scheme. This setup allows multiple derived classes to inherit from a single base class.

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
$vbLabelText   $csharpLabel

Multilevel Inheritance

A class functions as both a base class and a derived class in multilevel inheritance. This creates a chain of inheritance where each class builds upon its predecessor.

class Animal { /* Base class */ }

class Mammal : Animal { /* Derived class from Animal */ }

class Dog : Mammal { /* Derived class from Mammal */ }
class Animal { /* Base class */ }

class Mammal : Animal { /* Derived class from Animal */ }

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

Friend Class Mammal
	Inherits Animal

End Class

Friend Class Dog
	Inherits Mammal

End Class
$vbLabelText   $csharpLabel

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 method implementations described in interfaces, thus achieving a kind of multiple inheritance.

interface ILogger
{
    void Log(string message);
}

class ConsoleLogger : ILogger // Derived class
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

class FileLogger : ILogger
{
    public void Log(string message)
    {
        // Code to log to a file
    }
}
interface ILogger
{
    void Log(string message);
}

class ConsoleLogger : ILogger // Derived class
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

class FileLogger : ILogger
{
    public void Log(string message)
    {
        // Code to log to a file
    }
}
Friend Interface ILogger
	Sub Log(ByVal message As String)
End Interface

Friend Class ConsoleLogger ' Derived 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
		' Code to log to a file
	End Sub
End Class
$vbLabelText   $csharpLabel

Abstract Classes and Methods

In C#, an abstract class serves as a base class and cannot be instantiated on its own. Its purpose is to provide a common interface and set of methods for its derived classes. Abstract methods in such a base class must be implemented by derived classes.

abstract class Shape
{
    public abstract double Area(); // Abstract method
}

class Circle : 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 Circle : 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 Circle
	Inherits Shape

	Public Property Radius() As Double
	Public Overrides Function Area() As Double
		Return Math.PI * Math.Pow(Radius, 2)
	End Function
End Class
$vbLabelText   $csharpLabel

These are examples of inheritance in C#. The chosen method depends on the required flexibility, relationship between classes, and design goals.

IronPDF

The .NET library IronPDF allows programmers to create, edit, and modify PDF documents using C#. IronPDF offers various utilities to manage PDF tasks, such as generating PDFs from HTML, converting HTML to PDF, merging or splitting PDF documents, and annotating PDFs. For more information, refer to the IronPDF documentation.

Install IronPDF

To use IronPDF, you need to install it. You can use the following command in the Package Manager Console:

Install-Package IronPdf

or

Install-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.

Alternatively, use the NuGet Package Manager to search and install "IronPDF."

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

IronPDF enhances the ease of working with PDF documents in C#. By incorporating IronPDF with inherited classes, you can extend the functionality of your application to create and manipulate PDFs effortlessly.

The Advantages of Inheritance with IronPDF

  • Organized Code Structure: Inheritance promotes a well-organized code structure. You can create classes that specifically handle PDFs with IronPDF while maintaining a clean codebase.
  • Code Reusability: By extending base classes, you can reuse code effectively. This is particularly beneficial when working with libraries like IronPDF, as you can encapsulate common PDF operations in a base class for reuse.

Extending IronPDF Capabilities

To extend the capabilities of PdfDocument for IronPDF integration, let's create a class named IronPdfDocument:

using IronPdf;

public class IronPdfDocument : PdfDocument
{
    // Additional properties or methods specific to IronPDF can be added here

    // Method to convert HTML to PDF
    public void ConvertToPdf()
    {
        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

    // Method to convert HTML to PDF
    public void ConvertToPdf()
    {
        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

	' Method to convert HTML to PDF
	Public Sub ConvertToPdf()
		Dim Renderer = New IronPdf.HtmlToPdf()
		Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello, World</h1>")
		PDF.SaveAs("Output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

This IronPdfDocument class extends PdfDocument to facilitate easy PDF handling with IronPDF.

Building a PDF Report Generator

Let's use inheritance and IronPDF to create a simple PDF report generator. First, we define a Report base class:

public class Report
{
    // Base method for generating a 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
{
    // Base method for generating a 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
	' Base method for generating a 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
$vbLabelText   $csharpLabel

Now, we create a PdfReport derived class that incorporates IronPDF specifics:

public class PdfReport : Report
{
    // Override method to customize PDF report generation
    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 for PDF generation with IronPDF
    }
}
public class PdfReport : Report
{
    // Override method to customize PDF report generation
    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 for PDF generation with IronPDF
    }
}
Public Class PdfReport
	Inherits Report

	' Override method to customize PDF report generation
	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 for PDF generation with IronPDF
	End Sub
End Class
$vbLabelText   $csharpLabel

In this example, the PdfReport class inherits from Report and overrides the GenerateReport method to include custom logic for IronPDF-based PDF generation.

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

For more information on converting an HTML string to PDF, refer to the HTML to PDF example.

Conclusion

Inheritance, when paired with libraries like IronPDF, is a powerful feature that enhances the application development process. This post covered the basics of inheritance and provided a practical guide for integration with IronPDF.

Developing hierarchical class structures leads to a modular and structured codebase. Classes that inherit the general functions of base classes while addressing specific tasks demonstrate the benefits of reusability and extensibility. Integrating IronPDF elevates these advantages, offering seamless PDF management in your C# applications.

IronPDF's $749 Light pack includes a permanent license, upgrade options, and a year of software support. During the watermarked trial period, you can assess the software in real application environments. For more details on IronPDF's pricing, licensing, and trial version, visit the IronPDF licensing page. Explore the official Iron Software website for more Iron Software products.

Frequently Asked Questions

What is inheritance in C#?

Inheritance in C# is a key concept of object-oriented programming that allows a derived class to inherit traits and characteristics from a base class. It is implemented by using the colon ':' symbol followed by the base class name.

How does single inheritance work in C#?

In C#, single inheritance means a class can inherit from only one base class. This allows the derived class to extend the capabilities of the base class.

What is hierarchical inheritance?

Hierarchical inheritance occurs when multiple classes inherit from a single base class. This setup allows each derived class to have a common base.

Can C# support multiple inheritance?

C# does not support multiple inheritance directly, but it can be achieved through interface inheritance, where a class implements multiple interfaces.

What are abstract classes and methods in C#?

Abstract classes in C# serve as base classes that cannot be instantiated. They can contain abstract methods, which must be implemented by derived classes.

How can a library be integrated with inherited classes in C#?

A library can be integrated with inherited classes to extend functionality for creating and manipulating specified tasks in C# applications by encapsulating operations in base classes.

Why is inheritance beneficial when using a library in C#?

Inheritance promotes organized code structure and reusability, allowing developers to extend base classes for specific operations using a library, maintaining a clean codebase.

How can I install a library in a C# project?

You can install a library using the Package Manager Console with a specific command or use the NuGet Package Manager to search for and install it.

What is multilevel inheritance in C#?

Multilevel inheritance in C# involves a chain of inheritance where a derived class functions as a base class for another derived class, allowing each class to build upon its predecessor.

What is the purpose of a report generator using inheritance?

A report generator using inheritance allows for a modular design where a base class handles general report generation, and derived classes customize creation with library specifics.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.