Saltar al pie de página
.NET AYUDA

C# Switch Pattern Matching (Cómo Funciona para Desarrolladores)

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.

Preguntas Frecuentes

¿Cómo se puede aplicar la coincidencia de patrones de switch en el procesamiento de documentos en C#?

La coincidencia de patrones de switch en C# se puede utilizar para simplificar la lógica de toma de decisiones compleja. Al integrarse con una biblioteca de PDF como IronPDF, permite a los desarrolladores gestionar las tareas de procesamiento de documentos de manera más efectiva al agilizar la lógica de decisiones y mejorar la legibilidad del código.

¿Cuáles son las ventajas de usar la coincidencia de patrones de switch sobre las declaraciones tradicionales de if-else?

La coincidencia de patrones de switch proporciona una forma más concisa y legible de manejar múltiples condiciones en comparación con las declaraciones tradicionales de if-else. Mejora la mantenibilidad del código de C#, especialmente cuando se trata de tareas complejas de procesamiento de documentos usando IronPDF.

¿Cómo facilita la coincidencia de patrones de switch la automatización de documentos PDF?

La coincidencia de patrones de switch facilita la automatización de documentos PDF al permitir a los desarrolladores construir una lógica más limpia para gestionar diversas acciones y tipos de datos de documentos. Al usarse con IronPDF, ayuda a automatizar los flujos de trabajo y agilizar los procesos de extracción de datos.

¿Puede la coincidencia de patrones de switch manejar flujos de trabajo de documentos complejos en C#?

Sí, la coincidencia de patrones de switch es adecuada para manejar flujos de trabajo de documentos complejos en C#. Simplifica la lógica necesaria para gestionar diferentes tipos de documentos y acciones, especialmente cuando se usa junto a bibliotecas robustas como IronPDF.

¿Cómo implementas la coincidencia de patrones de switch en una aplicación de procesamiento de PDF en C#?

En una aplicación de procesamiento de PDF en C#, puedes implementar la coincidencia de patrones de switch usando la declaración switch con sintaxis de coincidencia de patrones para gestionar diferentes tipos de documentos o condiciones de procesamiento. IronPDF se puede utilizar para encargarse de las tareas de manipulación concreta de PDF.

¿Qué desafíos pueden enfrentar los desarrolladores al usar la coincidencia de patrones de switch en C#?

Los desarrolladores pueden enfrentar desafíos con la coincidencia de patrones de switch al tratar con patrones dinámicos o basados en tiempo de ejecución que requieren una lógica más compleja. Sin embargo, cuando se usa correctamente con una biblioteca como IronPDF, puede mejorar significativamente la eficiencia del código.

¿Cómo contribuye la coincidencia de patrones de switch a la mantenibilidad del código?

La coincidencia de patrones de switch contribuye a la mantenibilidad del código al proporcionar una forma clara y concisa de manejar múltiples condiciones. Esto reduce la complejidad y facilita la comprensión y modificación del código, especialmente en aplicaciones a gran escala que utilizan IronPDF.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más