Saltar al pie de página
.NET AYUDA

Declaración switch en C# (Cómo funciona para desarrolladores)

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.

Preguntas Frecuentes

¿Cómo mejora una sentencia de cambio la legibilidad del código en C#?

Una sentencia de cambio mejora la legibilidad del código en C# al proporcionar una forma estructurada de manejar múltiples condiciones, reduciendo la complejidad de las sentencias if-else anidadas. Permite a los desarrolladores delinear claramente diferentes caminos de ejecución del código basados en valores de variables.

¿Cuál es una aplicación práctica de las sentencias de cambio en la generación de PDF?

Las sentencias de cambio pueden utilizarse en la generación de PDF para crear dinámicamente diferentes tipos de PDFs basados en la entrada del usuario. Por ejemplo, usar una sentencia de cambio con IronPDF te permite decidir entre generar un informe o una factura PDF, facilitando así las tareas de gestión de documentos.

¿Cómo puede el pattern matching mejorar las sentencias de cambio en C#?

El pattern matching, introducido en C# 7.0, mejora las sentencias de cambio al permitir un código más expresivo y flexible. Incluye patrones de tipo y patrones de propiedad, lo que permite realizar comprobaciones de condiciones complejas y mejorar la legibilidad del código dentro de los bloques de cambio.

¿Qué avances trajo C# 8.0 a las sentencias de cambio?

C# 8.0 introdujo las expresiones de cambio, que proporcionan una forma más concisa de las sentencias de cambio. Este avance permite una lógica condicional más corta y elegante, haciendo el código más fácil de leer y mantener.

¿Por qué podría un desarrollador elegir una sentencia de cambio sobre sentencias if-else en C#?

Un desarrollador podría elegir una sentencia de cambio sobre sentencias if-else para mejorar la organización y legibilidad del código. Las sentencias de cambio categorizan la ejecución del código basada en los valores de variables, evitando la complejidad y desorden de las estructuras if-else anidadas.

¿Pueden las sentencias de cambio integrarse con bibliotecas de PDF para una funcionalidad mejorada?

Sí, las sentencias de cambio pueden integrarse con bibliotecas de PDF como IronPDF para mejorar la funcionalidad. Permiten la toma de decisiones dinámica en los procesos de generación de PDF, como la selección de diferentes plantillas o tipos de documentos basados en condiciones específicas.

¿Cómo funciona el caso por defecto en una sentencia de cambio en C#?

El caso por defecto en una sentencia de cambio en C# se ejecuta cuando ninguno de los casos especificados coincide con el valor de la variable. Actúa como un mecanismo de respaldo, asegurando que algún código se ejecute incluso si no se satisface ningún otro caso.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más