Zum Fußzeileninhalt springen
.NET HILFE

C# Switch-Fallmuster (Wie es für Entwickler funktioniert)

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.

Häufig gestellte Fragen

Wie kann C# Switch-Musterabgleich in der Dokumentenverarbeitung angewendet werden?

Switch-Musterabgleich in C# kann verwendet werden, um komplexe Entscheidungslogik zu vereinfachen. Bei der Integration mit einer PDF-Bibliothek wie IronPDF ermöglicht es Entwicklern, Dokumentenverarbeitungsaufgaben effektiver zu verwalten, indem es die Entscheidungslogik rationalisiert und die Lesbarkeit des Codes verbessert.

Welche Vorteile bietet der Switch-Musterabgleich gegenüber traditionellen if-else-Anweisungen?

Der Switch-Musterabgleich bietet eine prägnantere und lesbarere Möglichkeit, mehrere Bedingungen zu handhaben, verglichen mit traditionellen if-else-Anweisungen. Er verbessert die Wartbarkeit von C#-Code, insbesondere bei der Behandlung komplexer Dokumentenverarbeitungsaufgaben mit IronPDF.

Wie erleichtert der Switch-Musterabgleich die Automatisierung von PDF-Dokumenten?

Der Switch-Musterabgleich erleichtert die Automatisierung von PDF-Dokumenten, indem er Entwicklern ermöglicht, sauberere Logik zum Verwalten verschiedener Dokumentaktionen und Datentypen zu erstellen. In Verbindung mit IronPDF hilft er, Workflows zu automatisieren und Datenextraktionsprozesse zu rationalisieren.

Kann der Switch-Musterabgleich komplexe Dokumenten-Workflows in C# handhaben?

Ja, der Switch-Musterabgleich eignet sich gut zur Handhabung komplexer Dokumenten-Workflows in C#. Er vereinfacht die benötigte Logik zum Verwalten unterschiedlicher Dokumententypen und -aktionen, insbesondere in Kombination mit robusten Bibliotheken wie IronPDF.

Wie implementiert man den Switch-Musterabgleich in einer C#-PDF-Verarbeitungsanwendung?

In einer C#-PDF-Verarbeitungsanwendung können Sie den Switch-Musterabgleich implementieren, indem Sie die switch-Anweisung mit Musterabgleich-Syntax verwenden, um verschiedene Dokumententypen oder Verarbeitungsbedingungen zu verwalten. IronPDF kann verwendet werden, um die eigentlichen PDF-Bearbeitungsaufgaben zu erledigen.

Vor welchen Herausforderungen könnten Entwickler beim Einsatz des Switch-Musterabgleichs in C# stehen?

Entwickler könnten bei der Arbeit mit dynamischen oder zur Laufzeit basierenden Mustern, die komplexere Logik erfordern, Herausforderungen beim Switch-Musterabgleich begegnen. Bei korrekter Verwendung mit einer Bibliothek wie IronPDF kann er jedoch die Codeeffizienz erheblich verbessern.

Wie trägt der Switch-Musterabgleich zur Wartbarkeit des Codes bei?

Der Switch-Musterabgleich trägt zur Wartbarkeit des Codes bei, indem er eine klare und prägnante Möglichkeit bietet, mehrere Bedingungen zu behandeln. Dies verringert die Komplexität und macht den Code leichter verständlich und veränderbar, insbesondere in groß angelegten Anwendungen mit IronPDF.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen