푸터 콘텐츠로 바로가기
.NET 도움말

C# Case Statement (How it Works For Developers)

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;
}
$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;
}
$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;
$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);
$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
};
$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);
$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"
};
$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");
    }
}
$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");
    }
}
$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#.

자주 묻는 질문

스위치 문을 사용하여 C#에서 PDF 처리를 관리하려면 어떻게 해야 하나요?

스위치 문을 사용하여 페이지 수 또는 문서 유형과 같은 조건에 따라 다양한 PDF 작업을 실행하여 PDF 처리를 관리할 수 있는 IronPDF와 같은 라이브러리를 사용할 수 있습니다.

C#에서 스위치 문과 스위치 표현식의 차이점은 무엇인가요?

스위치 문은 중단 문을 사용하여 여러 조건을 처리하는 구조화된 방법을 제공하므로 중단 문이 필요 없는 반면, 스위치 표현식은 보다 간결하고 값을 반환하며 중단 문이 필요하지 않습니다.

C# 스위치 문에서 기본 대소문자가 중요한 이유는 무엇인가요?

기본 대소문자는 표현식과 일치하는 대소문자가 없을 때 대체 작업을 제공하여 오류를 방지하고 예기치 않은 값을 우아하게 처리할 수 있도록 하기 때문에 매우 중요합니다.

스위치 표현식은 C#에서 코드 가독성을 어떻게 향상시키나요?

스위치 표현식은 조건부 분기를 위한 간결한 구문을 제공하여 코드 가독성을 향상시켜 개발자가 보다 간결한 형태로 논리를 표현할 수 있도록 함으로써 코드를 더 쉽게 이해하고 유지 관리할 수 있게 해줍니다.

C# 애플리케이션에서 오류 처리에 스위치 문을 사용할 수 있나요?

예. 스위치 문은 오류 코드 또는 조건에 따라 프로그램을 특정 오류 처리 루틴으로 안내하여 오류 처리에 사용할 수 있으므로 C# 애플리케이션의 견고성을 향상시킬 수 있습니다.

IronPDF에서 스위치 문을 사용하는 실제 예는 무엇인가요?

실제적인 예로는 스위치 문을 사용하여 페이지 수 또는 기타 기준에 따라 PDF 문서에 다른 워터마크를 적용하고, PDF 조작 작업에 IronPDF를 활용하는 것을 들 수 있습니다.

IronPDF는 어떻게 스위치 기반 PDF 작업을 용이하게 하나요?

IronPDF는 PDF 변환, 편집, 렌더링과 같은 작업에 스위치 문을 사용하여 조건부로 트리거할 수 있는 강력한 도구와 메서드를 제공함으로써 스위치 기반 PDF 작업을 용이하게 합니다.

PDF 처리에서 스위치 문에 대한 일반적인 사용 사례에는 어떤 것이 있나요?

일반적인 사용 사례에는 문서 메타데이터에 따라 다른 처리 규칙을 적용하는 것(예: 문서 유형이나 내용에 따라 특정 서식 또는 변환 적용)이 포함됩니다.

IronPDF는 스위치 문으로 읽기 쉽고 유지 관리 가능한 코드를 만드는 데 어떻게 도움을 줄 수 있나요?

IronPDF는 스위치 문을 사용하여 구성할 수 있는 포괄적인 PDF 조작 방법을 제공하여 구조화된 로직으로 인해 가독성과 유지 관리가 모두 가능한 코드를 생성할 수 있도록 지원합니다.

의사 결정에서 switch 문은 if-else 블록에 비해 어떤 이점이 있나요?

스위치 문은 여러 개별 조건을 처리할 때 보다 체계적이고 오류 발생 가능성이 적은 구조를 제공하여 코드의 명확성을 높이고 긴 if-else 체인에 비해 오류 발생 가능성을 줄여줍니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.