Skip to footer content
.NET HELP

C# Switch Pattern Matching (How it Works for Developers)

Working with PDF files in C# often involves handling different types of documents, actions, or data sources. Traditionally, developers might rely on long if-else chains or nested switch statements to manage various input values and types or output decisions. But with modern C# features like switch pattern matching, your code can become far more elegant, readable, and maintainable.

When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing. In this article, we'll explore how to use C#'s advanced pattern matching features—such as type patterns, property patterns, and relational patterns—alongside IronPDF to streamline your PDF generation workflows.

What is Switch Pattern Matching in C#?

Switch pattern matching is a feature introduced in C# 7 and continually improved in later versions. Unlike traditional switch statements that match constant values only, pattern matching enables you to evaluate types, properties, and conditions within a single expression. The following example demonstrates how this feature works.

Example Syntax

switch (input)
{
    case int i when i > 0:
        Console.WriteLine("Positive integer");
        break;
    case string s:
        Console.WriteLine($"It's a string: {s}");
        break;
    default:
        Console.WriteLine("Unknown type");
        break;
}
switch (input)
{
    case int i when i > 0:
        Console.WriteLine("Positive integer");
        break;
    case string s:
        Console.WriteLine($"It's a string: {s}");
        break;
    default:
        Console.WriteLine("Unknown type");
        break;
}
Select Case input
'INSTANT VB TODO TASK: The following 'case' pattern variable is not converted by Instant VB:
'ORIGINAL LINE: case int i when i > 0:
	Case Integer i [when] i > 0
		Console.WriteLine("Positive integer")
'INSTANT VB TODO TASK: The following 'case' pattern variable is not converted by Instant VB:
'ORIGINAL LINE: case string s:
	Case String s
		Console.WriteLine($"It's a string: {s}")
	Case Else
		Console.WriteLine("Unknown type")
End Select
$vbLabelText   $csharpLabel

This code uses type patterns, relational operators, and a null constant pattern to handle multiple cases concisely. This technique significantly improves code readability with more concise syntax and supports more complex logic.

Why Combine Switch Pattern Matching with IronPDF?

C# Switch Pattern Matching (How it Works for Developers): Figure 1 - IronPDF homepage

IronPDF is a powerful .NET component for generating and manipulating PDFs from HTML, images, or raw text. Many real-world use cases involve processing different patterns of input: some documents might originate from URLs, others from HTML strings, and others from file uploads.

Rather than testing expressions with clunky if conditions, switch pattern matching allows you to support pattern-based logic efficiently. It lets you define how your application responds to different object types, specified constants, or even Boolean expressions—using the input expression itself to drive the workflow.

Common Use Cases in IronPDF with Pattern Matching

In the previous example we looked at how the basic syntax looks, but now let's look at it in action. The following code examples are some real-world PDF tasks that benefit from combining IronPDF with C# pattern matching.

1. Handle Multiple Input Formats with Type and Property Patterns

Let’s say your method accepts various input formats: HTML, a Uri, or a local .html file. Using type patterns, property patterns, and null patterns, you can distinguish these cases effortlessly.

using System;
using System.IO;
using IronPdf;
class Program
{
    static void Main()
    {
        object input = new Uri("https://example.com"); // Try changing this to: "<html><body>Hello</body></html>" or new FileInfo("sample.html")
        var renderer = new ChromePdfRenderer();
        PdfDocument pdfDoc = input switch
        {
            string html when html.StartsWith("<html>") =>
                renderer.RenderHtmlAsPdf(html),
            Uri url =>
                renderer.RenderUrlAsPdf(url.ToString()),
            FileInfo { Extension: ".html" } file =>
                renderer.RenderHtmlAsPdf(File.ReadAllText(file.FullName)),
            null => throw new ArgumentNullException("Input was null."),
            _ => throw new ArgumentException("Unsupported input type for PDF conversion.")
        };
        pdfDoc.SaveAs("example-input-types.pdf");
        Console.WriteLine("PDF created: example-input-types.pdf");
    }
}
using System;
using System.IO;
using IronPdf;
class Program
{
    static void Main()
    {
        object input = new Uri("https://example.com"); // Try changing this to: "<html><body>Hello</body></html>" or new FileInfo("sample.html")
        var renderer = new ChromePdfRenderer();
        PdfDocument pdfDoc = input switch
        {
            string html when html.StartsWith("<html>") =>
                renderer.RenderHtmlAsPdf(html),
            Uri url =>
                renderer.RenderUrlAsPdf(url.ToString()),
            FileInfo { Extension: ".html" } file =>
                renderer.RenderHtmlAsPdf(File.ReadAllText(file.FullName)),
            null => throw new ArgumentNullException("Input was null."),
            _ => throw new ArgumentException("Unsupported input type for PDF conversion.")
        };
        pdfDoc.SaveAs("example-input-types.pdf");
        Console.WriteLine("PDF created: example-input-types.pdf");
    }
}
Imports System
Imports System.IO
Imports IronPdf
Friend Class Program
	Shared Sub Main()
		Dim input As Object = New Uri("https://example.com") ' Try changing this to: "<html><body>Hello</body></html>" or new FileInfo("sample.html")
		Dim renderer = New ChromePdfRenderer()
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'		PdfDocument pdfDoc = input switch
'		{
'			string html when html.StartsWith("<html>") => renderer.RenderHtmlAsPdf(html),
'			Uri url =>
'				renderer.RenderUrlAsPdf(url.ToString()),
'			FileInfo { Extension: ".html" } file =>
'				renderer.RenderHtmlAsPdf(File.ReadAllText(file.FullName)),
'			null => throw new ArgumentNullException("Input was null."),
'			_ => throw new ArgumentException("Unsupported input type for PDF conversion.")
'		};
		pdfDoc.SaveAs("example-input-types.pdf")
		Console.WriteLine("PDF created: example-input-types.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Here, the property pattern (FileInfo { Extension: ".html" }) and null constant pattern (case null) make the logic more expressive and robust.

2. Dynamically Format PDFs with Positional and Declaration Patterns

Suppose you’re using a PdfRequest record that includes a format string. You can apply positional patterns, declaration patterns, and string constants to customize PDF formatting.

using System;
using IronPdf;
public record PdfRequest(string Title, string Content, string Format);
class Program
{
    static void Main()
    {
        PdfRequest request = new("My Report", "<h1>Monthly Report</h1><p>Generated by IronPDF.</p>", "A4");
        var renderer = new ChromePdfRenderer();
        // Use fully qualified enum to avoid IronWord conflict
        renderer.RenderingOptions = request switch
        {
            PdfRequest { Format: "A4" } => new IronPdf.ChromePdfRenderOptions
            {
                PaperSize = IronPdf.Rendering.PdfPaperSize.A4
            },
            PdfRequest { Format: "Letter" } => new IronPdf.ChromePdfRenderOptions
            {
                PaperSize = IronPdf.Rendering.PdfPaperSize.Letter
            },
            _ => new IronPdf.ChromePdfRenderOptions
            {
                PaperSize = IronPdf.Rendering.PdfPaperSize.Legal // Fallback
            }
        };
        var pdf = renderer.RenderHtmlAsPdf(request.Content);
        pdf.SaveAs("example-formatted.pdf");
        Console.WriteLine("PDF created: example-formatted.pdf");
    }
}
using System;
using IronPdf;
public record PdfRequest(string Title, string Content, string Format);
class Program
{
    static void Main()
    {
        PdfRequest request = new("My Report", "<h1>Monthly Report</h1><p>Generated by IronPDF.</p>", "A4");
        var renderer = new ChromePdfRenderer();
        // Use fully qualified enum to avoid IronWord conflict
        renderer.RenderingOptions = request switch
        {
            PdfRequest { Format: "A4" } => new IronPdf.ChromePdfRenderOptions
            {
                PaperSize = IronPdf.Rendering.PdfPaperSize.A4
            },
            PdfRequest { Format: "Letter" } => new IronPdf.ChromePdfRenderOptions
            {
                PaperSize = IronPdf.Rendering.PdfPaperSize.Letter
            },
            _ => new IronPdf.ChromePdfRenderOptions
            {
                PaperSize = IronPdf.Rendering.PdfPaperSize.Legal // Fallback
            }
        };
        var pdf = renderer.RenderHtmlAsPdf(request.Content);
        pdf.SaveAs("example-formatted.pdf");
        Console.WriteLine("PDF created: example-formatted.pdf");
    }
}
Imports System
Imports IronPdf
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record PdfRequest(string Title, string Content, string Format)
Friend Class Program
	Shared Sub Main()
		Dim request As New PdfRequest("My Report", "<h1>Monthly Report</h1><p>Generated by IronPDF.</p>", "A4")
		Dim renderer = New ChromePdfRenderer()
		' Use fully qualified enum to avoid IronWord conflict
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'		renderer.RenderingOptions = request switch
'		{
'			PdfRequest { Format: "A4" } => new IronPdf.ChromePdfRenderOptions
'			{
'				PaperSize = IronPdf.Rendering.PdfPaperSize.A4
'			},
'			PdfRequest { Format: "Letter" } => new IronPdf.ChromePdfRenderOptions
'			{
'				PaperSize = IronPdf.Rendering.PdfPaperSize.Letter
'			},
'			_ => new IronPdf.ChromePdfRenderOptions
'			{
'				PaperSize = IronPdf.Rendering.PdfPaperSize.Legal // Fallback
'			}
'		};
		Dim pdf = renderer.RenderHtmlAsPdf(request.Content)
		pdf.SaveAs("example-formatted.pdf")
		Console.WriteLine("PDF created: example-formatted.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

This usage demonstrates how the expression matches the corresponding property within the record, following logical patterns based on expected values.

Output Sizes

C# Switch Pattern Matching (How it Works for Developers): Figure 2 - Size difference in PDF outputs

3. Role-Based PDFs Using Var and Not Patterns

Use var patterns and not patterns to handle user roles while avoiding null or unexpected states.

using System;
using IronPdf;
public abstract record UserRole;
public record Admin(string Email) : UserRole;
public record Viewer(string Email) : UserRole;
public record Guest() : UserRole;
class Program
{
    static void Main()
    {
        UserRole currentUser = new Admin("admin@example.com"); // Try changing to Viewer or Guest
        var pdf = currentUser switch
        {
            Admin { Email: var email } =>
                new ChromePdfRenderer().RenderHtmlAsPdf($"<h1>Admin Dashboard</h1><p>Email: {email}</p>"),
            Viewer =>
                new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Viewer Summary</h1><p>Access limited.</p>"),
            Guest =>
                new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Guest Mode</h1><p>Please sign in.</p>"),
            not null =>
                throw new UnauthorizedAccessException("Unknown role type."),
            null =>
                throw new ArgumentNullException("Role cannot be null.")
        };
        pdf.SaveAs("example-role.pdf");
        Console.WriteLine("PDF created: example-role.pdf");
    }
}
using System;
using IronPdf;
public abstract record UserRole;
public record Admin(string Email) : UserRole;
public record Viewer(string Email) : UserRole;
public record Guest() : UserRole;
class Program
{
    static void Main()
    {
        UserRole currentUser = new Admin("admin@example.com"); // Try changing to Viewer or Guest
        var pdf = currentUser switch
        {
            Admin { Email: var email } =>
                new ChromePdfRenderer().RenderHtmlAsPdf($"<h1>Admin Dashboard</h1><p>Email: {email}</p>"),
            Viewer =>
                new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Viewer Summary</h1><p>Access limited.</p>"),
            Guest =>
                new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Guest Mode</h1><p>Please sign in.</p>"),
            not null =>
                throw new UnauthorizedAccessException("Unknown role type."),
            null =>
                throw new ArgumentNullException("Role cannot be null.")
        };
        pdf.SaveAs("example-role.pdf");
        Console.WriteLine("PDF created: example-role.pdf");
    }
}
Imports System
Imports IronPdf
Public MustOverride ReadOnly Property UserRole() As record
public record Admin(String Email) : UserRole
public record Viewer(String Email) : UserRole
public record Guest() : UserRole
Dim Program As class
If True Then
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	static void Main()
'	{
'		UserRole currentUser = New Admin("admin@example.com"); ' Try changing to Viewer or Guest
''INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
''		var pdf = currentUser switch
''		{
''			Admin { Email: var email } => new ChromePdfRenderer().RenderHtmlAsPdf($"<h1>Admin Dashboard</h1><p>Email: {email}</p>"),
''			Viewer =>
''				new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Viewer Summary</h1><p>Access limited.</p>"),
''			Guest =>
''				new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Guest Mode</h1><p>Please sign in.</p>"),
''			not null =>
''				throw new UnauthorizedAccessException("Unknown role type."),
''			null =>
''				throw new ArgumentNullException("Role cannot be null.")
''		};
'		pdf.SaveAs("example-role.pdf");
'		Console.WriteLine("PDF created: example-role.pdf");
'	}
End If
$vbLabelText   $csharpLabel

This structure improves security and code readability, while leveraging temporary variable declarations like var email. The following image shows the different PDF documents created based on different input values.

C# Switch Pattern Matching (How it Works for Developers): Figure 3 - Role-based output

4. Relational Pattern Matching Based on User Data

Need to generate different PDFs depending on user levels? Try using two relational patterns to test if the input falls within a certain range.

using System;
using IronPdf;
class Program
{
    static void Main()
    {
        int userScore = 85; // Try other values: 45, 70, 101
        string message = userScore switch
        {
            < 60 => "Needs Improvement",
            >= 60 and < 80 => "Satisfactory",
            >= 80 and <= 100 => "Excellent",
            _ => "Invalid score"
        };
        var html = $"<h1>Score Report</h1><p>Score: {userScore}</p><p>Result: {message}</p>";
        var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(html);
        pdf.SaveAs("example-score.pdf");
        Console.WriteLine("PDF created: example-score.pdf");
    }
}
using System;
using IronPdf;
class Program
{
    static void Main()
    {
        int userScore = 85; // Try other values: 45, 70, 101
        string message = userScore switch
        {
            < 60 => "Needs Improvement",
            >= 60 and < 80 => "Satisfactory",
            >= 80 and <= 100 => "Excellent",
            _ => "Invalid score"
        };
        var html = $"<h1>Score Report</h1><p>Score: {userScore}</p><p>Result: {message}</p>";
        var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(html);
        pdf.SaveAs("example-score.pdf");
        Console.WriteLine("PDF created: example-score.pdf");
    }
}
Imports System
Imports IronPdf
Friend Class Program
	Shared Sub Main()
		Dim userScore As Integer = 85 ' Try other values: 45, 70, 101
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'		string message = userScore switch
'		{
'			< 60 => "Needs Improvement",
'			>= 60 and < 80 => "Satisfactory",
'			>= 80 and <= 100 => "Excellent",
'			_ => "Invalid score"
'		};
		Dim html = $"<h1>Score Report</h1><p>Score: {userScore}</p><p>Result: {message}</p>"
		Dim pdf = (New ChromePdfRenderer()).RenderHtmlAsPdf(html)
		pdf.SaveAs("example-score.pdf")
		Console.WriteLine("PDF created: example-score.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

The relational operators and boolean expressions keep the code concise and expressive.

Output

C# Switch Pattern Matching (How it Works for Developers): Figure 4 - Score-based output

Tips for Implementing This Pattern in Your Projects

C# Switch Pattern Matching (How it Works for Developers): Figure 5 - C# Pattern Matching Cheat Sheet

  • Use record types for clean and immutable data objects.
  • Prefer switch expressions over if-else trees for cleaner logic.
  • Use not patterns and discard patterns (_) to ignore irrelevant matches.
  • Add default cases to catch unknown inputs early.
  • Break out complex cases into helper methods for readability.

Real-World Benefits

  • Cleaner Code: No more deeply nested if-else or switch-case blocks
  • Easier Testing: Isolated pattern cases simplify unit testing
  • Flexibility: Easily extend logic when adding new input types
  • Better Separation of Concerns: Focus logic only on input/output transformation

Conclusion: Modernize Your PDF Logic

Switch pattern matching is more than just a syntactic improvement, it's a powerful paradigm for writing safer, more expressive code. Combined with IronPDF's flexible rendering capabilities, you can create smarter and more scalable document generation pipelines with minimal code.

Whether you're building a report generator, a document previewer, or a dynamic template system, try adding pattern matching to your IronPDF implementation. You'll quickly see the benefits in clarity, control, and maintainability.

Want To Try IronPDF for Yourself?

Download the free trial to try out IronPDF's powerful features for yourself before purchasing a license.

Frequently Asked Questions

What is switch pattern matching in C#?

Switch pattern matching in C# is a feature that allows developers to perform complex data evaluations and decision-making. It enables cleaner and more readable code, especially when working with multiple conditions or data types.

How does switch pattern matching enhance document processing?

When combined with a powerful PDF library like IronPDF, switch pattern matching allows developers to build smarter and cleaner logic for document processing, reducing complexity and improving performance.

What are the benefits of using IronPDF with C# switch pattern matching?

IronPDF, when used with C# switch pattern matching, enhances document processing by simplifying code structure and improving efficiency in handling complex document logic.

Can switch pattern matching handle different data types in C#?

Yes, switch pattern matching in C# can handle different data types, enabling developers to write more versatile and adaptable code by evaluating data types within a switch statement.

Is switch pattern matching suitable for large-scale applications?

Switch pattern matching is suitable for large-scale applications as it helps in writing clean, organized, and maintainable code, especially when combined with robust libraries like IronPDF.

What specific features of IronPDF complement switch pattern matching?

IronPDF offers features such as PDF creation, manipulation, and conversion, which complement switch pattern matching by providing a robust framework for handling complex logic in document workflows.

How does switch pattern matching improve code readability?

Switch pattern matching improves code readability by allowing developers to write concise and clear code structures, making it easier to understand and maintain, especially in complex decision-making scenarios.

What role does switch pattern matching play in optimizing C# applications?

Switch pattern matching optimizes C# applications by reducing code complexity and improving logic flow, which can lead to better performance and easier debugging.

Are there any limitations to using switch pattern matching in C#?

While switch pattern matching is powerful, it may have limitations in scenarios requiring dynamic or runtime-based pattern evaluations. Careful design is needed to ensure optimal use.

Why should developers consider using IronPDF with switch pattern matching?

Developers should consider using IronPDF with switch pattern matching to leverage the strengths of both, allowing for efficient and effective document processing and logic implementation in their applications.

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.