Zum Fußzeileninhalt springen
.NET HILFE

C# Case Statement (Wie es für Entwickler funktioniert)

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
$vbLabelText   $csharpLabel
  • 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

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
'};
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

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"
'};
$vbLabelText   $csharpLabel

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#

C# Case Statement (How it Works For Developers): Figure 1 - IronPDF

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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

Here is the output PDF file of one page:

C# Case Statement (How it Works For Developers): Figure 2 - Output

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#.

Häufig gestellte Fragen

Wie kann ich eine Switch-Anweisung verwenden, um die PDF-Verarbeitung in C# zu verwalten?

Sie können eine Switch-Anweisung verwenden, um die PDF-Verarbeitung zu verwalten, indem Sie verschiedene PDF-Operationen basierend auf Bedingungen wie Seitenanzahl oder Dokumenttyp mit einer Bibliothek wie IronPDF ausführen.

Was ist der Unterschied zwischen einer Switch-Anweisung und einem Switch-Ausdruck in C#?

Eine Switch-Anweisung bietet eine strukturierte Möglichkeit, mehrere Bedingungen mit Break-Anweisungen zu behandeln, um Fall-Through zu verhindern, während ein Switch-Ausdruck prägnanter ist, einen Wert zurückgibt und Break-Anweisungen überflüssig macht.

Warum ist der Standardfall in C#-Switch-Anweisungen wichtig?

Der Standardfall ist entscheidend, da er sicherstellt, dass unerwartete Werte ordentlich behandelt werden, indem ein Fallback für den Fall bereitgestellt wird, dass keine Bedingung mit dem Ausdruck übereinstimmt.

Wie verbessern Switch-Ausdrücke die Lesbarkeit des Codes in C#?

Switch-Ausdrücke verbessern die Lesbarkeit des Codes, indem sie eine prägnante Syntax für bedingte Verzweigungen bieten, die es Entwicklern ermöglicht, Logik in kompakterer Form auszudrücken, was den Code leichter verständlich und wartbar macht.

Können Switch-Anweisungen zur Fehlerbehandlung in C#-Anwendungen verwendet werden?

Ja, Switch-Anweisungen können zur Fehlerbehandlung verwendet werden, indem sie das Programm basierend auf Fehlercodes oder Bedingungen zu spezifischen Fehlerbehandlungsroutinen leiten und damit die Robustheit von C#-Anwendungen verbessern.

Was ist ein praktisches Beispiel für die Verwendung einer Switch-Anweisung mit IronPDF?

Ein praktisches Beispiel ist die Verwendung einer Switch-Anweisung, um unterschiedliche Wasserzeichen auf ein PDF-Dokument anzuwenden, basierend auf seiner Seitenanzahl oder anderen Kriterien, unter Nutzung von IronPDF für die PDF-Manipulationsaufgaben.

Wie erleichtert IronPDF Switch-basierte PDF-Operationen?

IronPDF erleichtert Switch-basierte PDF-Operationen, indem es ein robustes Set an Werkzeugen und Methoden bereitstellt, die bedingt mittels Switch-Anweisungen für Aufgaben wie Umwandlung, Bearbeitung und Darstellung von PDFs ausgelöst werden können.

Welche häufigen Anwendungsfälle gibt es für Switch-Anweisungen in der PDF-Verarbeitung?

Häufige Anwendungsfälle umfassen die Anwendung unterschiedlicher Verarbeitungsregeln basierend auf Dokumentmetadaten, etwa die Anwendung spezifischer Formatierungen oder Umwandlungen basierend auf dem Dokumenttyp oder -inhalt.

Wie kann IronPDF dabei helfen, lesbaren und wartbaren Code mit Switch-Anweisungen zu erstellen?

IronPDF hilft, indem es umfassende Methoden zur PDF-Manipulation bereitstellt, die sich mit Switch-Anweisungen organisieren lassen und so zu verständlichem und wartbarem Code führen, dank der strukturierten Logik.

Welche Vorteile bieten Switch-Anweisungen im Vergleich zu if-else-Blöcken bei Entscheidungsfindungen?

Switch-Anweisungen bieten eine besser organisierte und weniger fehleranfällige Struktur zur Bearbeitung mehrerer diskreter Bedingungen und verbessern die Codeklarheit, wodurch die Wahrscheinlichkeit von Fehlern im Vergleich zu umfangreichen if-else-Ketten verringert wird.

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