Saltar al pie de página
.NET AYUDA

C# Declaración de caso (Cómo funciona para desarrolladores)

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

Preguntas Frecuentes

¿Cómo puedo usar una declaración de switch para gestionar el procesamiento de PDF en C#?

Puede usar una declaración de switch para gestionar el procesamiento de PDF ejecutando diferentes operaciones de PDF basadas en condiciones, como el recuento de páginas o el tipo de documento, usando una biblioteca como IronPDF.

¿Cuál es la diferencia entre una declaración de switch y una expresión de switch en C#?

Una declaración de switch proporciona una forma estructurada de manejar múltiples condiciones con declaraciones de break para prevenir caídas, mientras que una expresión de switch es más concisa, devuelve un valor y elimina la necesidad de declaraciones de break.

¿Por qué es importante el caso predeterminado en las declaraciones de switch de C#?

El caso predeterminado es crucial ya que asegura que los valores inesperados se manejen de manera adecuada, previniendo errores al proporcionar una acción de reserva cuando ningún caso coincide con la expresión.

¿Cómo mejoran las expresiones de switch la legibilidad del código en C#?

Las expresiones de switch mejoran la legibilidad del código proporcionando una sintaxis concisa para la bifurcación condicional, permitiendo a los desarrolladores expresar la lógica de forma más compacta, lo que hace que el código sea más fácil de entender y mantener.

¿Pueden las declaraciones de switch usarse para el manejo de errores en aplicaciones C#?

Sí, las declaraciones de switch pueden usarse para el manejo de errores al dirigir el programa a rutinas específicas de manejo de errores basadas en códigos de error o condiciones, mejorando así la robustez de las aplicaciones C#.

¿Cuál es un ejemplo práctico de usar una declaración de switch con IronPDF?

Un ejemplo práctico es usar una declaración de switch para aplicar diferentes marcas de agua a un documento PDF basado en su recuento de páginas u otros criterios, aprovechando IronPDF para las tareas de manipulación de PDF.

¿Cómo facilita IronPDF las operaciones de PDF basadas en switch?

IronPDF facilita las operaciones de PDF basadas en switch al proporcionar un conjunto robusto de herramientas y métodos que pueden activarse de manera condicional usando declaraciones de switch para tareas como la conversión, edición y renderizado de PDFs.

¿Cuáles son algunos casos de uso comunes para declaraciones de switch en el procesamiento de PDF?

Los casos de uso comunes incluyen aplicar diferentes reglas de procesamiento basadas en los metadatos del documento, como aplicar un formato o conversiones específicas basadas en el tipo o contenido del documento.

¿Cómo puede IronPDF ayudar en la creación de código legible y mantenible con declaraciones de switch?

IronPDF ayuda ofreciendo métodos completos de manipulación de PDF que pueden organizarse usando declaraciones de switch, resultando en un código que es tanto legible como mantenible debido a su lógica estructurada.

¿Qué ventajas ofrecen las declaraciones de switch sobre los bloques if-else en la toma de decisiones?

Las declaraciones de switch ofrecen una estructura más organizada y menos propensa a errores para manejar múltiples condiciones discretas, mejorando la claridad del código y reduciendo la probabilidad de errores en comparación con largas cadenas de if-else.

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