Skip to footer content
.NET HELP

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

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 capabilities and use cases 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
$vbLabelText   $csharpLabel

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 its own 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 the virtual method of its parent.

// Non-abstract class
public class Animal
{
    // Virtual method with a default implementation
    public virtual void Speak()
    {
        Console.WriteLine("Some generic animal sound");
    }
}
// Non-abstract class
public class Animal
{
    // Virtual method with a default implementation
    public virtual void Speak()
    {
        Console.WriteLine("Some generic animal sound");
    }
}
' Non-abstract class
Public Class Animal
	' Virtual method with a default implementation
	Public Overridable Sub Speak()
		Console.WriteLine("Some generic animal sound")
	End Sub
End Class
$vbLabelText   $csharpLabel

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

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
{
    // Override the abstract method
    public override void DisplayInfo()
    {
        Console.WriteLine("This is a car.");
    }

    // Override the virtual method
    public override void StartEngine()
    {
        Console.WriteLine("Car engine started with custom settings.");
    }
}
public class Car : Vehicle
{
    // Override the abstract method
    public override void DisplayInfo()
    {
        Console.WriteLine("This is a car.");
    }

    // Override the virtual method
    public override void StartEngine()
    {
        Console.WriteLine("Car engine started with custom settings.");
    }
}
Public Class Car
	Inherits Vehicle

	' Override the abstract method
	Public Overrides Sub DisplayInfo()
		Console.WriteLine("This is a car.")
	End Sub

	' Override the virtual method
	Public Overrides Sub StartEngine()
		Console.WriteLine("Car engine started with custom settings.")
	End Sub
End Class
$vbLabelText   $csharpLabel

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 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
{
    // Override the StartEngine method
    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
{
    // Override the StartEngine method
    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

	' Override the StartEngine method
	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
$vbLabelText   $csharpLabel

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# Virtual 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, 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();

        // 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");

        // 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");

        // 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();

        // 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");

        // 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");

        // 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()

		' 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")

		' 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")

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

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

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# Virtual Vs Abstract (How It Works For Developers): Figure 2 - Report Output

Conclusion

C# Virtual 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 licensing options, with licenses starting from $749, providing a comprehensive solution for your PDF needs.

Frequently Asked Questions

What is the difference between virtual and abstract methods in C#?

Virtual methods in C# have a default implementation and can be overridden in derived classes, while abstract methods must be overridden in derived classes and do not have an implementation in the base class.

When should you use abstract methods?

You should use abstract methods when all derived classes need to provide their own implementation of a method, ensuring that specific behaviors are defined in each derived class.

When should you use virtual methods?

Use virtual methods when you want to provide a default implementation that derived classes can optionally override to add or change behavior.

Can a class have both abstract and virtual methods?

Yes, a class can have both abstract and virtual methods. Abstract methods must be overridden in derived classes, while virtual methods have a default implementation that can be optionally overridden.

How does a PDF library integrate with C# projects?

IronPDF is a library for generating, editing, and reading PDF documents within .NET applications. It allows developers to create PDFs from HTML strings, files, and URLs, ensuring layouts and styles are retained.

What is an abstract class in C#?

An abstract class in C# is a class that cannot be instantiated directly and serves as a blueprint for other classes. It may contain abstract methods that must be implemented in derived classes.

What is an example of using virtual methods?

An example is a base class 'Animal' with a virtual method 'Speak' that provides a default implementation. Derived classes can override this method to specify different sounds for different animals.

Can virtual methods be overridden multiple times in the inheritance chain?

Yes, virtual methods can be overridden in any derived class along the inheritance chain, allowing each class to provide its specific implementation or extend the functionality further.

How do you override a virtual method in a derived class?

To override a virtual method in a derived class, use the 'override' keyword followed by the method's signature. This allows you to provide a new implementation or extend the existing one.

What are the benefits of using abstract and virtual methods in C#?

Abstract and virtual methods promote flexibility, reusability, and maintainability in code by allowing for polymorphic behavior and customization in derived classes.

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.
Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?

Nuget Passed