.NET HELP

C# Vitrual Vs Abstract (How It Works For Developers)

Published April 29, 2024
Share:

In C#, virtual methods can be overridden in derived classes, while abstract methods must be overridden in derived classes. This allows for flexible behavior and enables polymorphism in object-oriented programming. These two concepts allow for flexibility and reusability in object-oriented programming. This article explains the specifics of abstract and virtual methods, providing clear examples and focusing on their practical uses in coding. We'll also explore IronPDF later in the article.

Abstract Class and Methods

An abstract class is a special type of class that cannot be instantiated directly. Instead, it serves as a blueprint for other classes. An abstract class may contain abstract methods, which are methods declared in the abstract class but must be implemented in concrete-derived classes.

public abstract class Vehicle
{
// abstract method to be implemented in non abstract child class
    public abstract void DisplayInfo();
}
public abstract class Vehicle
{
// abstract method to be implemented in non abstract child class
    public abstract void DisplayInfo();
}
Public MustInherit Class Vehicle
' abstract method to be implemented in non abstract child class
	Public MustOverride Sub DisplayInfo()
End Class
VB   C#

In this example, the Vehicle class is abstract, and DisplayInfo is an abstract method. The DisplayInfo method doesn't have any implementation in the Vehicle class. It forces the derived class to provide their definition of this method.

Virtual Methods

Virtual methods are methods in a base class that have a default implementation but can be overridden in derived classes. The virtual keyword is used to declare a method as virtual. Derived classes use the override keyword to provide a specific implementation of the method, which helps to understand how a child class can override virtual method of its parent.

// non abstract class
public class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Some generic animal sound");
    }
}
// non abstract class
public class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Some generic animal sound");
    }
}
' non abstract class
Public Class Animal
	Public Overridable Sub Speak()
		Console.WriteLine("Some generic animal sound")
	End Sub
End Class
VB   C#

Here, the Animal class has a virtual method Speak with a default implementation. Derived classes can override the method to provide a specific animal sound using the override keyword.

Combining Virtual and Abstract Methods

A class can have both abstract and virtual methods. Abstract methods do not have an implementation and must be overridden in derived classes, whereas virtual methods have a default implementation that derived classes can override optionally.

Consider a scenario where you're building a system that models different types of vehicles, each with its way of displaying information. Here's how you can use abstract and virtual methods:

public abstract class Vehicle
{
    // Abstract method
    public abstract void DisplayInfo();
    // Virtual method
    public virtual void StartEngine()
    {
        Console.WriteLine("Engine started with default configuration.");
    }
}
public abstract class Vehicle
{
    // Abstract method
    public abstract void DisplayInfo();
    // Virtual method
    public virtual void StartEngine()
    {
        Console.WriteLine("Engine started with default configuration.");
    }
}
Public MustInherit Class Vehicle
	' Abstract method
	Public MustOverride Sub DisplayInfo()
	' Virtual method
	Public Overridable Sub StartEngine()
		Console.WriteLine("Engine started with default configuration.")
	End Sub
End Class
VB   C#

In this Vehicle class, DisplayInfo is an abstract method, forcing all derived classes to implement their way of displaying information. StartEngine, however, provides a default way to start the engine, which can be overridden by an inherited class if needed.

Example with Derived Classes

Now, let's define a Car class, a non-abstract child class, that inherits from Vehicle and implements the abstract method while optionally overriding the virtual method:

public class Car : Vehicle
{
// public override void abstractmethod
    public override void DisplayInfo()
    {
        Console.WriteLine("This is a car.");
    }
    public override void StartEngine()
    {
        Console.WriteLine("Car engine started with custom settings.");
    }
}
public class Car : Vehicle
{
// public override void abstractmethod
    public override void DisplayInfo()
    {
        Console.WriteLine("This is a car.");
    }
    public override void StartEngine()
    {
        Console.WriteLine("Car engine started with custom settings.");
    }
}
Public Class Car
	Inherits Vehicle

' public override void abstractmethod
	Public Overrides Sub DisplayInfo()
		Console.WriteLine("This is a car.")
	End Sub
	Public Overrides Sub StartEngine()
		Console.WriteLine("Car engine started with custom settings.")
	End Sub
End Class
VB   C#

Here, the Car class provides specific implementations for both the abstract method DisplayInfo and the virtual method StartEngine.

Difference and When to Use

  • Use abstract methods when all derived classes must provide their own implementation of a method.
  • Use virtual methods when derived classes should have the option to override a default or provide additional behaviors.

Abstract and virtual methods are powerful features in C# that enable you to write more maintainable and reusable code. By defining all the methods in a base class as abstract or virtual, you can dictate which methods must be overridden in derived classes and which methods can optionally be overridden to modify or extend the default behavior.

Overriding Virtual Methods

Overriding virtual methods in derived classes allows for custom behavior while retaining the option to call the base class implementation. This is achieved using the base keyword.

Example of Overriding and Calling Base Implementation

public class ElectricCar : Car
{
    public override void StartEngine()
    {
        base.StartEngine(); // Call the base class implementation
        Console.WriteLine("Electric car engine started with energy-saving mode.");
    }
}
public class ElectricCar : Car
{
    public override void StartEngine()
    {
        base.StartEngine(); // Call the base class implementation
        Console.WriteLine("Electric car engine started with energy-saving mode.");
    }
}
Public Class ElectricCar
	Inherits Car

	Public Overrides Sub StartEngine()
		MyBase.StartEngine() ' Call the base class implementation
		Console.WriteLine("Electric car engine started with energy-saving mode.")
	End Sub
End Class
VB   C#

In this example, ElectricCar, which is a child class of Car, overrides the StartEngine method inherited from its parent class. It calls the base class implementation and adds additional behavior specific to electric cars.

Implementing Abstract and Non-Abstract Class

It's essential to understand the practical differences and applications of abstract and non-abstract classes in software development. Abstract classes serve as a template for other classes, while non-abstract classes are used to instantiate objects. The choice between using an abstract class and a non-abstract class depends on whether you need to create a base class that should not be instantiated on its own.

IronPDF: C# PDF Library

C# Vitrual Vs Abstract (How It Works For Developers): Figure 1 - IronPDF

IronPDF is a comprehensive PDF library designed for generating, editing, and reading PDF documents directly within .NET applications. This tool stands out for its ability to create PDFs directly from HTML strings, HTML files, and URLs. Developers can create, modify, and extract PDF content programmatically in C# projects. Let's explore an example of IronPDF in the context of our article.

The main capability of IronPDF is converting HTML to PDF, ensuring that layouts and styles are retained. This tool is great for creating PDFs from web content for reports, invoices, and documentation. It supports the conversion of HTML files, URLs, and HTML strings to PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

Code Example

Here's a straightforward actual code example to illustrate the use of virtual and abstract keywords in the context of extending IronPDF functionalities:

public abstract class PdfReportGenerator
{
    // Use abstract method to force derived classes to implement their custom PDF generation logic.
    public abstract void GenerateReport(string filePath);
    // A virtual function allows derived classes to override the default implementation of PDF setup.
    public virtual void SetupPdfGenerator()
    {
        // Default PDF setup logic that can be overridden by derived classes.
        IronPdf.Installation.TempFolderPath = @"F:\TempPdfFiles";
    }
}
public class MonthlyReportGenerator : PdfReportGenerator
{
    // Override abstract method to provide specific implementation using override modifier.
    public override void GenerateReport(string filePath)
    {
        var pdf = new ChromePdfRenderer();
        pdf.RenderHtmlAsPdf("<h1>Monthly Report</h1> <p>Add Your report content here....</p>").SaveAs(filePath);
    }
    // Optionally override the virtual method to customize the setup.
    public override void SetupPdfGenerator()
    {
        base.SetupPdfGenerator();
        // Additional setup logic specific to monthly reports.
        IronPdf.Installation.TempFolderPath = @"F:\MonthlyReports";
    }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        PdfReportGenerator reportGenerator = new MonthlyReportGenerator();
        reportGenerator.SetupPdfGenerator();
        reportGenerator.GenerateReport(@"F:\MonthlyReports\MonthlyReport.pdf");
        Console.WriteLine("Report generated successfully.");
    }
}
public abstract class PdfReportGenerator
{
    // Use abstract method to force derived classes to implement their custom PDF generation logic.
    public abstract void GenerateReport(string filePath);
    // A virtual function allows derived classes to override the default implementation of PDF setup.
    public virtual void SetupPdfGenerator()
    {
        // Default PDF setup logic that can be overridden by derived classes.
        IronPdf.Installation.TempFolderPath = @"F:\TempPdfFiles";
    }
}
public class MonthlyReportGenerator : PdfReportGenerator
{
    // Override abstract method to provide specific implementation using override modifier.
    public override void GenerateReport(string filePath)
    {
        var pdf = new ChromePdfRenderer();
        pdf.RenderHtmlAsPdf("<h1>Monthly Report</h1> <p>Add Your report content here....</p>").SaveAs(filePath);
    }
    // Optionally override the virtual method to customize the setup.
    public override void SetupPdfGenerator()
    {
        base.SetupPdfGenerator();
        // Additional setup logic specific to monthly reports.
        IronPdf.Installation.TempFolderPath = @"F:\MonthlyReports";
    }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        PdfReportGenerator reportGenerator = new MonthlyReportGenerator();
        reportGenerator.SetupPdfGenerator();
        reportGenerator.GenerateReport(@"F:\MonthlyReports\MonthlyReport.pdf");
        Console.WriteLine("Report generated successfully.");
    }
}
Public MustInherit Class PdfReportGenerator
	' Use abstract method to force derived classes to implement their custom PDF generation logic.
	Public MustOverride Sub GenerateReport(ByVal filePath As String)
	' A virtual function allows derived classes to override the default implementation of PDF setup.
	Public Overridable Sub SetupPdfGenerator()
		' Default PDF setup logic that can be overridden by derived classes.
		IronPdf.Installation.TempFolderPath = "F:\TempPdfFiles"
	End Sub
End Class
Public Class MonthlyReportGenerator
	Inherits PdfReportGenerator

	' Override abstract method to provide specific implementation using override modifier.
	Public Overrides Sub GenerateReport(ByVal filePath As String)
		Dim pdf = New ChromePdfRenderer()
		pdf.RenderHtmlAsPdf("<h1>Monthly Report</h1> <p>Add Your report content here....</p>").SaveAs(filePath)
	End Sub
	' Optionally override the virtual method to customize the setup.
	Public Overrides Sub SetupPdfGenerator()
		MyBase.SetupPdfGenerator()
		' Additional setup logic specific to monthly reports.
		IronPdf.Installation.TempFolderPath = "F:\MonthlyReports"
	End Sub
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		Dim reportGenerator As PdfReportGenerator = New MonthlyReportGenerator()
		reportGenerator.SetupPdfGenerator()
		reportGenerator.GenerateReport("F:\MonthlyReports\MonthlyReport.pdf")
		Console.WriteLine("Report generated successfully.")
	End Sub
End Class
VB   C#

In this custom implementation example, PdfReportGenerator is an abstract class defining a contract for generating PDF reports with a method to generate the report and a virtual method for setup that can be optionally overridden. MonthlyReportGenerator is a concrete implementation that provides the specifics for generating a monthly report and customizes the setup by overriding the virtual method.

C# Vitrual Vs Abstract (How It Works For Developers): Figure 2 - Report Output

Conclusion

C# Vitrual Vs Abstract (How It Works For Developers): Figure 3 - Licensing

Understanding and using virtual and abstract methods effectively can significantly enhance your C# programming. Remember, abstract methods require a derived class to provide an implementation, while virtual methods allow for an optional override of a default implementation. IronPDF library offers a free trial, and licenses start from $749, providing a comprehensive solution for your PDF needs.

< PREVIOUS
C# Partial (How It Works For Developers)
NEXT >
How to Generate PDF Reports using the ASP.NET

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >