Zum Fußzeileninhalt springen
.NET HILFE

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

In the vast landscape of programming languages, enhancing code readability and efficiency is paramount, and the C# language stands as a stalwart as it provides diverse constructs to aid in your coding needs. Among its arsenal of powerful tools, the "C# Switch Statement" stands out prominently. This comprehensive guide will explore the nuanced intricacies of them within the C# language. We will delve into its multifaceted uses and illuminate its practical application through a real-world scenario involving IronPDF, a versatile C# library for PDF generation. This journey aims not only to unravel its mechanics but also to underscore its significance in the broader landscape of C# development.

1. Understanding the Switch Statement

The switch statement in C# is a control flow statement that allows developers to write cleaner and more concise code when dealing with multiple conditions. It is particularly useful when you want to perform differing actions based on a particular variable's value.

This makes it a perfect alternative to if-else statements when the keyword/variable is the central focus, as it increases the code's readability and ability to be maintained. Unlike an if-else statement, which can lead to nested structures and potential code complexity, the switch statement provides a more organized alternative. It is especially beneficial when working with a variable that needs to trigger distinct actions based on its value.

Now, let's take a closer look at the role of breaking within the context of a switch statement. In C#, the break statement is used to terminate the execution of a block of code associated with a particular case within the switch block. When a match or switch case matches, and the code block corresponding to that case is executed, the break statement is crucial in preventing the subsequent cases from being evaluated. If you wish to incorporate fall-through behavior within your statement, you should use the goto statement instead of break.

Here's a basic structure of a switch statement in C#:

switch (variable)
{
    case value1:
        // Code to be executed if variable equals value1
        break;
    case value2:
        // Code to be executed if variable equals value2
        break;
    // More cases can be added as needed
    default:
        // Default Case to be executed if none of the cases match
        break;
}
switch (variable)
{
    case value1:
        // Code to be executed if variable equals value1
        break;
    case value2:
        // Code to be executed if variable equals value2
        break;
    // More cases can be added as needed
    default:
        // Default Case to be executed if none of the cases match
        break;
}
Select Case variable
	Case value1
		' Code to be executed if variable equals value1
	Case value2
		' Code to be executed if variable equals value2
	' More cases can be added as needed
	Case Else
		' Default Case to be executed if none of the cases match
End Select
$vbLabelText   $csharpLabel

Now, let's explore the different types of switch statements and their use cases.

2. Types of Switch Statements and Their Uses

2.1. Simple Switch Statement

This is the most basic form of a switch statement. It compares the variable with constant values and executes the code block associated with the first matching value or case. If no match is found, the default block of code is executed.

int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    // More cases...
    default:
        Console.WriteLine("Invalid day");
        break;
}
int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    // More cases...
    default:
        Console.WriteLine("Invalid day");
        break;
}
Dim day As Integer = 3
Select Case day
	Case 1
		Console.WriteLine("Monday")
	Case 2
		Console.WriteLine("Tuesday")
	' More cases...
	Case Else
		Console.WriteLine("Invalid day")
End Select
$vbLabelText   $csharpLabel

2.2. Switch Statement with Patterns (C# 7.0 and later)

C# 7.0 introduced case pattern matching which allowed for a more expressive and flexible switch statement. A pattern match expression can include type patterns, property patterns, and more, making the code even more readable.

object obj = "Hello";
switch (obj)
{
    case string s:
        Console.WriteLine($"String of length {s.Length}");
        break;
    case int i:
        Console.WriteLine($"Integer: {i}");
        break;
    // More cases...
    default:
        Console.WriteLine("Other type");
        break;
}
object obj = "Hello";
switch (obj)
{
    case string s:
        Console.WriteLine($"String of length {s.Length}");
        break;
    case int i:
        Console.WriteLine($"Integer: {i}");
        break;
    // More cases...
    default:
        Console.WriteLine("Other type");
        break;
}
Dim obj As Object = "Hello"
Select Case obj
'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($"String of length {s.Length}")
'INSTANT VB TODO TASK: The following 'case' pattern variable is not converted by Instant VB:
'ORIGINAL LINE: case int i:
	Case Integer i
		Console.WriteLine($"Integer: {i}")
	' More cases...
	Case Else
		Console.WriteLine("Other type")
End Select
$vbLabelText   $csharpLabel

2.3. Switch Expression (C# 8.0 and later)

In C# 8.0, a new and more concise form of switch statement is introduced as switch expressions. They can be used in places where constant expression of a value is needed, making the code shorter and more elegant.

int day = 2;
string result = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    // More cases...
    _ => "Invalid day"
};
Console.WriteLine(result);
int day = 2;
string result = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    // More cases...
    _ => "Invalid day"
};
Console.WriteLine(result);
Dim day As Integer = 2
Dim tempVar As String
Select Case day
	Case 1
		tempVar = "Monday"
	Case 2
		tempVar = "Tuesday"
	' More cases...
	Case Else
		tempVar = "Invalid day"
End Select
Dim result As String = tempVar
Console.WriteLine(result)
$vbLabelText   $csharpLabel

Now that we have a solid understanding of switch statements, let's see how they can be applied in a real-world scenario using IronPDF in C#.

3. Introducing IronPDF in C#

IronPDF is a popular C# library that allows developers to generate and manipulate PDF documents with ease. It simplifies tasks related to PDF file creation, editing, and rendering. Let's explore how the switch statement can be employed with IronPDF to enhance the functionality and organization of your coding.

3.1. Using Switch Statement with IronPDF

Suppose you are working on a document management system where you need to generate different types of PDFs based on the usage case of a document content. Here's how you can leverage the switch statement with IronPDF:

using IronPdf;
using System;

class GeneratePDF
{
    public static void Main(String[] args)
    {
        var renderer = new ChromePdfRenderer();
        string userInput;

        Console.WriteLine("Enter your input:");
        Console.WriteLine("Enter 'I' for Invoice");
        Console.WriteLine("Enter 'R' for Report");
        userInput = Console.ReadLine();

        switch (userInput)
        {
            case "R":
                // Render and save a PDF for a report
                var reportPdf = renderer.RenderHtmlFileAsPdf("report.html");
                reportPdf.SaveAs("Report.pdf");
                break;
            case "I":
                // Render and save a PDF for an invoice
                var invoicePdf = renderer.RenderHtmlFileAsPdf("invoice.html");
                invoicePdf.SaveAs("Invoice.pdf");
                break;
            default:
                Console.WriteLine("Invalid input");
                break;
        }
    }
}
using IronPdf;
using System;

class GeneratePDF
{
    public static void Main(String[] args)
    {
        var renderer = new ChromePdfRenderer();
        string userInput;

        Console.WriteLine("Enter your input:");
        Console.WriteLine("Enter 'I' for Invoice");
        Console.WriteLine("Enter 'R' for Report");
        userInput = Console.ReadLine();

        switch (userInput)
        {
            case "R":
                // Render and save a PDF for a report
                var reportPdf = renderer.RenderHtmlFileAsPdf("report.html");
                reportPdf.SaveAs("Report.pdf");
                break;
            case "I":
                // Render and save a PDF for an invoice
                var invoicePdf = renderer.RenderHtmlFileAsPdf("invoice.html");
                invoicePdf.SaveAs("Invoice.pdf");
                break;
            default:
                Console.WriteLine("Invalid input");
                break;
        }
    }
}
Imports IronPdf
Imports System

Friend Class GeneratePDF
	Public Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim userInput As String

		Console.WriteLine("Enter your input:")
		Console.WriteLine("Enter 'I' for Invoice")
		Console.WriteLine("Enter 'R' for Report")
		userInput = Console.ReadLine()

		Select Case userInput
			Case "R"
				' Render and save a PDF for a report
				Dim reportPdf = renderer.RenderHtmlFileAsPdf("report.html")
				reportPdf.SaveAs("Report.pdf")
			Case "I"
				' Render and save a PDF for an invoice
				Dim invoicePdf = renderer.RenderHtmlFileAsPdf("invoice.html")
				invoicePdf.SaveAs("Invoice.pdf")
			Case Else
				Console.WriteLine("Invalid input")
		End Select
	End Sub
End Class
$vbLabelText   $csharpLabel

This C# program utilizes the IronPDF library to dynamically generate PDF files based on user input. The user is prompted to enter either 'I' for Invoice or 'R' for Report. Depending on the input, the program uses the ChromePdfRenderer class to render the corresponding HTML file ("report.html" for Report or "invoice.html" for Invoice) into a PDF format. The generated PDF is then saved with appropriate filenames, "Report.pdf" for the Report and "Invoice.pdf" for the Invoice. This approach provides a flexible and interactive way to generate specific types of PDF documents through a console interface.

3.2. Example of Report

In the following example, we will create a report using input from the user.

Console Input:

C# Switch Statement (How It Works For Developers) Figure 1 - User input in Console (Report)

Output PDF:

C# Switch Statement (How It Works For Developers) Figure 2 - Output PDF Report

3.3. Example of Invoice

In this case statement example, we will create an Invoice using input from the user and a switch statement.

Console Input:

C# Switch Statement (How It Works For Developers) Figure 3 - User input in Console (Invoice)

Output PDF:

C# Switch Statement (How It Works For Developers) Figure 4 - Output PDF (Invoice)

4. Conclusion

In conclusion, the C# switch statement stands out as a robust control flow tool that offers developers a more organized and concise approach to handling multiple conditions compared to traditional if-else statements. By categorizing code execution based on variable values, switch statements can contribute to your coding through improved readability and maintainability.

The versatility of switch statements is demonstrated through various types, including simple switches, pattern-based switch blocks, and switch expressions, each catering to specific coding scenarios.

The integration of the IronPDF library exemplifies the practical application of switch statements in generating dynamic PDF documents based on user input and showcases how this feature can be harnessed in real-world scenarios to enhance the flexibility and efficiency of your C# coding.

To explore the capabilities of IronPDF and learn more about HTML to PDF conversion, visit the IronPDF tutorials.

Häufig gestellte Fragen

Wie verbessert eine Switch-Anweisung die Lesbarkeit des Codes in C#?

Eine Switch-Anweisung verbessert die Lesbarkeit des Codes in C#, indem sie eine strukturierte Methode zur Behandlung mehrerer Bedingungen bietet, wodurch die Komplexität von verschachtelten If-Else-Anweisungen reduziert wird. Sie ermöglicht Entwicklern, verschiedene Ausführungspfade des Codes basierend auf Variablenwerten klar zu unterscheiden.

Was ist eine praktische Anwendung von Switch-Anweisungen in der PDF-Erstellung?

Switch-Anweisungen können in der PDF-Erstellung verwendet werden, um basierend auf Benutzereingaben dynamisch verschiedene Arten von PDFs zu erstellen. Beispielsweise ermöglicht es eine Switch-Anweisung mit IronPDF, zwischen der Erstellung eines Berichts oder einer Rechnung zu entscheiden und so Aufgaben im Dokumentenmanagement zu rationalisieren.

Wie kann Musterabgleich C#-Switch-Anweisungen verbessern?

Der in C# 7.0 eingeführte Musterabgleich verbessert Switch-Anweisungen, indem er eine ausdrucksstärkere und flexiblere Codierung ermöglicht. Er umfasst Typpatterns und Eigenschaftsmuster, die komplexe Bedingungsprüfungen ermöglichen und die Lesbarkeit des Codes innerhalb von Switch-Blöcken verbessern.

Welche Fortschritte brachte C# 8.0 für Switch-Anweisungen?

C# 8.0 führte Switch-Ausdrücke ein, die eine prägnantere Form von Switch-Anweisungen bieten. Dieser Fortschritt ermöglicht kürzere, elegantere bedingte Logik, die den Code leichter lesbar und wartbarer macht.

Warum könnte ein Entwickler eine Switch-Anweisung gegenüber If-Else-Anweisungen in C# wählen?

Ein Entwickler könnte eine Switch-Anweisung gegenüber If-Else-Anweisungen wählen, um die Organisation und Lesbarkeit des Codes zu verbessern. Switch-Anweisungen führen Codestrukturierungen basierend auf Variablenwerten durch und vermeiden die Komplexität und Unübersichtlichkeit verschachtelter If-Else-Strukturen.

Können Switch-Anweisungen mit PDF-Bibliotheken zur Verbesserung der Funktionalität integriert werden?

Ja, Switch-Anweisungen können mit PDF-Bibliotheken wie IronPDF zur Verbesserung der Funktionalität integriert werden. Sie ermöglichen dynamische Entscheidungen im PDF-Erstellungsprozess, z. B. die Auswahl verschiedener Vorlagen oder Dokumenttypen basierend auf bestimmten Bedingungen.

Wie funktioniert der Standardfall in einer C#-Switch-Anweisung?

Der Standardfall in einer C#-Switch-Anweisung wird ausgeführt, wenn keine der angegebenen Fällen mit dem Wert der Variable übereinstimmt. Er fungiert als Rückfallmechanismus, der sicherstellt, dass etwas Code ausgeführt wird, selbst wenn kein anderer Fall erfüllt ist.

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