Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
The switch statement in C# offers a more streamlined and readable alternative to multiple if-else expression statements. 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. This case statement evaluates an expression and executes static void main code based on the matching value, making it an integral part of decision-making in your code.
While if-else structures are great for simple conditions or checks, switch case statements shine 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 as compared to the if statement, which is crucial for both writing and maintaining the same code.
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 with any of the data types. It's an efficient alternative to using multiple if-else conditions, especially when dealing with a variable that can have several distinct values.
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 or fall through behavior
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 or fall through behavior
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 or fall through behavior
End Select
switch (variable)
: This is where you specify the variable or expression to evaluate as shown in the above program.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 optional goto
block executes if none of the specified cases match the variable.The break statement in the switch is crucial. It prevents the "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.
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.
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.
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, especially to handle unexpected or unknown values.
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.
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".
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.
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.
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.
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.
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: 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.
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
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;
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;
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
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")
Here is the output PDF file of one page:
In this tutorial, we've explored the switch case statement in C#, a way 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 create simple switch cases, handle various scenarios with the default case, and explore 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 valuable 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 $749, providing a comprehensive solution for all your PDF processing needs in C#.
9 .NET API products for your office documents