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
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?
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
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
This usage demonstrates how the expression matches the corresponding property within the record, following logical patterns based on expected values.
Output Sizes
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
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.
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
The relational operators and boolean expressions keep the code concise and expressive.
Output
Tips for Implementing This Pattern in Your Projects
- 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
How can C# switch pattern matching be applied to document processing?
Switch pattern matching in C# can be used to simplify complex decision-making logic. When integrated with a PDF library like IronPDF, it allows developers to manage document processing tasks more effectively by streamlining decision logic and improving code readability.
What are the advantages of using switch pattern matching over traditional if-else statements?
Switch pattern matching provides a more concise and readable way to handle multiple conditions compared to traditional if-else statements. It enhances the maintainability of C# code, especially when dealing with complex document processing tasks using IronPDF.
How does switch pattern matching facilitate PDF document automation?
Switch pattern matching facilitates PDF document automation by allowing developers to build cleaner logic for managing various document actions and data types. When used with IronPDF, it helps automate workflows and streamline data extraction processes.
Can switch pattern matching handle complex document workflows in C#?
Yes, switch pattern matching is well-suited for handling complex document workflows in C#. It simplifies the logic required for managing different document types and actions, especially when used alongside robust libraries like IronPDF.
How do you implement switch pattern matching in a C# PDF processing application?
In a C# PDF processing application, you can implement switch pattern matching by using the switch
statement with pattern matching syntax to manage different document types or processing conditions. IronPDF can be used to handle the actual PDF manipulation tasks.
What challenges might developers face when using switch pattern matching in C#?
Developers might face challenges with switch pattern matching when dealing with dynamic or runtime-based patterns that require more complex logic. However, when used correctly with a library like IronPDF, it can significantly enhance code efficiency.
How does switch pattern matching contribute to code maintainability?
Switch pattern matching contributes to code maintainability by providing a clear, concise way to handle multiple conditions. This reduces complexity and makes the code easier to understand and modify, especially in large-scale applications using IronPDF.