.NET HELP

C# Switch Statement (How it Works For Developers)

Published December 12, 2023
Share:

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. This journey aims not only to unravel it's 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 want to perform differing actions based on a particular variable's value.

This makes it a perfect alternative to if-else statements when keyword/variable is the center focus, as it increases the codes 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 above code and 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 a:
        // Code to be executed if variable equals value1
        break;
    case c:
        // 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 a:
        // Code to be executed if variable equals value1
        break;
    case c:
        // 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 a
		' Code to be executed if variable equals value1
	Case c
		' 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
VB   C#

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
VB   C#

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 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
VB   C#

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)
VB   C#

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. Now, 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 used case 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 mystring = null;
        Console.WriteLine("Enter your input : ");
        Console.WriteLine("Enter 'I' for Invoice");
        Console.WriteLine("Enter 'R' for Report");
        mystring = Console.ReadLine();
        switch (mystring)
        {
            case "R":
                var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");
                pdf.SaveAs("Report.pdf");
                break;
            case "I":
                var pdfi = renderer.RenderHtmlFileAsPdf("report.html");
                pdfi.SaveAs("Invoice.pdf");
                break;
        }
    }
}
using IronPdf;
using System;
class generatePDF {
    public static void Main(String [] args)
    {
        var renderer = new ChromePdfRenderer();
        string mystring = null;
        Console.WriteLine("Enter your input : ");
        Console.WriteLine("Enter 'I' for Invoice");
        Console.WriteLine("Enter 'R' for Report");
        mystring = Console.ReadLine();
        switch (mystring)
        {
            case "R":
                var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");
                pdf.SaveAs("Report.pdf");
                break;
            case "I":
                var pdfi = renderer.RenderHtmlFileAsPdf("report.html");
                pdfi.SaveAs("Invoice.pdf");
                break;
        }
    }
}
Imports IronPdf
Imports System
Friend Class generatePDF
	Public Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim mystring As String = Nothing
		Console.WriteLine("Enter your input : ")
		Console.WriteLine("Enter 'I' for Invoice")
		Console.WriteLine("Enter 'R' for Report")
		mystring = Console.ReadLine()
		Select Case mystring
			Case "R"
				Dim pdf = renderer.RenderHtmlFileAsPdf("invoice.html")
				pdf.SaveAs("Report.pdf")
			Case "I"
				Dim pdfi = renderer.RenderHtmlFileAsPdf("report.html")
				pdfi.SaveAs("Invoice.pdf")
		End Select
	End Sub
End Class
VB   C#

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 ("invoice.html" for Report or "report.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 this following example, we will create a report using Input from 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 Invoice using Input from User and 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 which 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 block, switches, 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.

IronPDF, allowing you to test its capabilities, to know more about the HTML to PDF conversion visit at the following link.

< PREVIOUS
Visual Studio Code C# (How it Works For Developers)
NEXT >
Solid Principles C# (How it Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >