C# Case Statement (How it Works For Developers)
The switch statement in C# offers a more streamlined and readable alternative to multiple if-else blocks. It's beneficial when you have a variable that can take one of several distinct values, and you need to execute different code based on the value. The switch statement evaluates an expression and executes code based on the matching value, making it an integral part of decision-making in your code.
While if-else structures are useful for simple conditions or checks, switch case statements excel when dealing with more complex condition checks, especially those based on a single variable or pattern match expression. They provide a cleaner and more understandable syntax compared to if statements, which is crucial for both writing and maintaining code.
Basics of the Switch Statement
What is a Switch Statement?
A switch statement in C# is a control structure used to select one of many code paths to execute. The selection is based on the value or an expression. It's an efficient alternative to using multiple if-else conditions, especially when dealing with a variable that can have several distinct values.
Syntax
The basic syntax of a switch statement is straightforward:
// Switch statement
switch (variable)
{
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
// More cases as needed
default:
// Code to execute if variable doesn't match any case
break;
}
// Switch statement
switch (variable)
{
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
// More cases as needed
default:
// Code to execute if variable doesn't match any case
break;
}
' Switch statement
Select Case variable
Case value1
' Code to execute if variable equals value1
Case value2
' Code to execute if variable equals value2
' More cases as needed
Case Else
' Code to execute if variable doesn't match any case
End Select
switch (variable)
: This specifies the variable or expression to evaluate.case value1
: These are the different values or conditions you check against the variable.break
: This keyword is used to exit the switch block once a matching case is executed.default
statement: This block executes if none of the specified cases match the variable.
Understanding the Break Statement
The break statement in the switch is crucial. It prevents "fall through" behavior, where execution moves to the subsequent case even if the matching condition is already met. Each case block typically ends with a break statement to ensure that only the code under the matching case is executed.
Comparing Switch Statement and If-Else Statements
While the structure of the if-else statement involves checking a condition and executing a block of code if the condition is true, switch statements compare a single variable or expression against multiple potential values. This makes the switch statement more concise and easier to read when you have many conditions or case patterns to check.
Example: Using a Switch Statement
int number = 3;
switch (number)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
Console.WriteLine("Three");
break;
default:
Console.WriteLine("Other Number"); // Print to console
break;
}
int number = 3;
switch (number)
{
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
Console.WriteLine("Three");
break;
default:
Console.WriteLine("Other Number"); // Print to console
break;
}
Dim number As Integer = 3
Select Case number
Case 1
Console.WriteLine("One")
Case 2
Console.WriteLine("Two")
Case 3
Console.WriteLine("Three")
Case Else
Console.WriteLine("Other Number") ' Print to console
End Select
In this example, the program will print "Three" as the output since the number matches case 3.
The Role of the Default Case
Understanding the Default in a Switch Block
In a switch statement, the default case plays a crucial role. It serves as a catch-all option that is executed when none of the specified case labels matches the switch expression's value. While it's optional, including a default case is good practice to handle unexpected or unknown values.
How and When to Use the Default Statement
The default case is used when you want to execute a block of code if none of the specific cases match. It ensures that the switch statement always has a defined behavior, regardless of the input. The default case is declared using the default
keyword, followed by a colon.
default:
// Code to execute if no case matches
break;
default:
// Code to execute if no case matches
break;
Case Else
' Code to execute if no case matches
break
The default case can be placed anywhere within the switch block but is typically placed at the end for readability.
Example: Switch Statement with Default Case
Consider a scenario where you're evaluating a day of the week:
int day = 5;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
Console.WriteLine(dayName);
int day = 5;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
Console.WriteLine(dayName);
Dim day As Integer = 5
Dim dayName As String
Select Case day
Case 1
dayName = "Monday"
Case 2
dayName = "Tuesday"
Case 3
dayName = "Wednesday"
Case 4
dayName = "Thursday"
Case 5
dayName = "Friday"
Case 6
dayName = "Saturday"
Case 7
dayName = "Sunday"
Case Else
dayName = "Invalid day"
End Select
Console.WriteLine(dayName)
In this example, if day
has a value other than 1 to 7, the default case is executed, setting dayName
to "Invalid day".
Best Practices for the Default Case
- Always Include a Default: Even if you believe you have covered all possible cases, include a default case to handle unforeseen values.
- Meaningful Actions: Use the default case to perform meaningful actions, like logging an error, setting a default value, or notifying the user of an unknown value.
Advanced Switch Features
Introduction to Switch Expressions in C#
With the evolution of C#, switch expressions were introduced as a more concise and expressive way of handling multiple conditional branches. Unlike traditional switch statements, switch expressions return a value and are more streamlined, making them a powerful tool in modern C# programming.
Syntax of Switch Expressions
The syntax of a switch expression in C# is a more compact form of the switch case statement. Here's a basic structure:
var result = variable switch
{
value1 => result1,
value2 => result2,
_ => defaultResult
};
var result = variable switch
{
value1 => result1,
value2 => result2,
_ => defaultResult
};
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'var result = variable switch
'{
' value1 => result1,
' value2 => result2,
' _ => defaultResult
'};
The underscore (_) symbol represents the default case in switch expressions, functioning similarly to the default block in traditional switch statements.
Example: Using a Switch Expression
Consider a scenario where you need to categorize a temperature reading:
int temperature = 25;
string weatherDescription = temperature switch
{
<= 0 => "Freezing",
< 20 => "Cold",
< 30 => "Mild",
_ => "Hot"
};
Console.WriteLine(weatherDescription);
int temperature = 25;
string weatherDescription = temperature switch
{
<= 0 => "Freezing",
< 20 => "Cold",
< 30 => "Mild",
_ => "Hot"
};
Console.WriteLine(weatherDescription);
Dim temperature As Integer = 25
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'string weatherDescription = temperature switch
'{
' <= 0 => "Freezing",
' < 20 => "Cold",
' < 30 => "Mild",
' _ => "Hot"
'};
Console.WriteLine(weatherDescription)
In this example, the switch expression succinctly categorizes the temperature, with the default case (_) covering any scenario not matched by the other cases.
Pattern Matching with Switch Expressions
Switch expressions in C# allow for pattern matching, making them even more versatile. You can match types, values, or even patterns:
object obj = // some object;
string description = obj switch
{
int i => $"Integer: {i}",
string s => $"String: {s}",
_ => "Unknown type"
};
object obj = // some object;
string description = obj switch
{
int i => $"Integer: {i}",
string s => $"String: {s}",
_ => "Unknown type"
};
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'object obj = string description = obj switch
'{
' int i => $"Integer: {i}",
' string s => $"String: {s}",
' _ => "Unknown type"
'};
C# Switch Statement vs. Switch Expression
- C# Switch Statement: Traditionally used for executing different blocks of code based on a variable's value. It requires a break statement for each case.
- Switch Expression: Introduced in C# 8.0, this provides a more concise syntax and is typically used when a value needs to be returned based on a condition.
Integrating Switch Statements with IronPDF in C#
Explore IronPDF Features is a .NET PDF library for creating, editing, and working with PDF documents. When combined with C# switch statements or expressions, it becomes a powerful tool for handling various PDF-related operations based on specific conditions. This integration is particularly useful for tasks that require decision-making based on PDF content or metadata.
IronPDF’s key feature is converting HTML to PDF with layouts and styles, while keeping layouts and styles intact. This is ideal for creating PDFs from web content, including reports, invoices, and documentation. HTML files, URLs, and HTML strings are all convertible into PDF files.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. 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");
// 2. 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");
// 3. 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();
// 1. 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");
// 2. 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");
// 3. 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()
' 1. 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")
' 2. 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")
' 3. 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
Example: Conditional Watermarking with IronPDF and Switch Statements
Let's consider a scenario where you have a PDF document, and you want to apply different watermarks based on page count based on the number of pages in the document. Here's how you can achieve this using IronPDF in combination with a C# switch statement:
using IronPdf;
class Program
{
static void Main(string[] args)
{
IronPdf.License.LicenseKey = "Your-License-Code";
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Define different watermark HTML for each case
string watermarkHtmlOnePage = "<div style='color:red;'>One Page Document</div>";
string watermarkHtmlTwoPage = "<div style='color:blue;'>Two Page Document</div>";
switch (pdf.PageCount)
{
case 1:
// Apply watermark for one-page document
pdf.ApplyWatermark(watermarkHtmlOnePage);
break;
case 2:
// Apply watermark for two-page documents
pdf.ApplyWatermark(watermarkHtmlTwoPage);
break;
default:
// Apply a default watermark for other cases
pdf.ApplyWatermark("<div style='color:green;'>Multiple Page Document</div>");
break;
}
// Save the watermarked PDF
pdf.SaveAs("watermarked.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
IronPdf.License.LicenseKey = "Your-License-Code";
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Define different watermark HTML for each case
string watermarkHtmlOnePage = "<div style='color:red;'>One Page Document</div>";
string watermarkHtmlTwoPage = "<div style='color:blue;'>Two Page Document</div>";
switch (pdf.PageCount)
{
case 1:
// Apply watermark for one-page document
pdf.ApplyWatermark(watermarkHtmlOnePage);
break;
case 2:
// Apply watermark for two-page documents
pdf.ApplyWatermark(watermarkHtmlTwoPage);
break;
default:
// Apply a default watermark for other cases
pdf.ApplyWatermark("<div style='color:green;'>Multiple Page Document</div>");
break;
}
// Save the watermarked PDF
pdf.SaveAs("watermarked.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
IronPdf.License.LicenseKey = "Your-License-Code"
Dim pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")
' Define different watermark HTML for each case
Dim watermarkHtmlOnePage As String = "<div style='color:red;'>One Page Document</div>"
Dim watermarkHtmlTwoPage As String = "<div style='color:blue;'>Two Page Document</div>"
Select Case pdf.PageCount
Case 1
' Apply watermark for one-page document
pdf.ApplyWatermark(watermarkHtmlOnePage)
Case 2
' Apply watermark for two-page documents
pdf.ApplyWatermark(watermarkHtmlTwoPage)
Case Else
' Apply a default watermark for other cases
pdf.ApplyWatermark("<div style='color:green;'>Multiple Page Document</div>")
End Select
' Save the watermarked PDF
pdf.SaveAs("watermarked.pdf")
End Sub
End Class
Here is the output PDF file of one page:
Conclusion
In this tutorial, we've explored the switch case statement in C#, a fundamental form of decision-making in programming. We started by understanding its basic structure and compared it with traditional if-else statements, highlighting its advantages in readability and simplicity for handling multiple conditions.
We created simple switch cases, handled various scenarios with the default case, and explored advanced features like switch expressions. The real-world application of switch statements was demonstrated through an example integrating IronPDF for dynamic PDF processing, showcasing how switch statements can be a valuable tool in a programmer's toolkit.
IronPDF offers a free trial for feature exploration, allowing you to explore its features and functionalities. For continued use and access to its full suite of tools, IronPDF licenses start from a competitive pricing model, providing a comprehensive solution for all your PDF processing needs in C#.
Frequently Asked Questions
What is a switch statement in C#?
A switch statement in C# is a control structure used to select one of many code paths to execute based on the value of a variable or an expression.
How does a switch statement differ from if-else statements?
Switch statements provide a cleaner and more concise syntax for handling multiple conditions compared to if-else statements, which are more suitable for simple condition checks.
What role does the default case play in a switch statement?
The default case serves as a catch-all option executed when none of the specified case labels match the switch expression's value, ensuring defined behavior for unexpected inputs.
What is a switch expression in C#?
Switch expressions in C# are a more concise and expressive way to handle multiple conditional branches, introduced in C# 8.0. They return a value and do not require break statements.
How can conditional logic be applied to PDF-related operations in C#?
Conditional logic can be applied to perform different PDF-related operations, such as applying different watermarks depending on the page count of a PDF document, using a switch statement and a PDF library like IronPDF.
What are some best practices for using the default case in switch statements?
Always include a default case to handle unforeseen values, and use it to perform meaningful actions like logging errors or setting default values.
What is the syntax for a basic switch statement in C#?
A basic switch statement in C# uses the following syntax: 'switch (variable) { case value1: // code break; ... default: // code break; }'.
How does pattern matching work with switch expressions?
Switch expressions in C# allow for pattern matching, enabling you to match types, values, or patterns, providing more versatility in handling conditions.
Can switch expressions be used to return values?
Yes, switch expressions are designed to return a value based on a condition, making them a powerful tool for concise and expressive code.
What is a useful .NET library for handling PDF documents?
A useful .NET library for handling PDF documents is IronPDF, which allows for creating, editing, and converting HTML to PDF while maintaining layouts and styles.