Przejdź do treści stopki
POMOC .NET

Instrukcja case w języku C# (jak działa dla programistów)

Instrukcja switch w języku C# stanowi bardziej uproszczoną i czytelniejszą alternatywę dla wielu bloków if-else. Jest to przydatne, gdy masz zmienną, która może przyjmować jedną z kilku różnych wartości, a musisz wykonać inny kod w zależności od tej wartości. Instrukcja switch ocenia wyrażenie i wykonuje kod w oparciu o pasującą wartość, co czyni ją integralną częścią procesu podejmowania decyzji w kodzie.

Podczas gdy konstrukcje if-else są przydatne w przypadku prostych warunków lub sprawdzeń, instrukcje switch case sprawdzają się doskonale przy bardziej złożonych sprawdzaniach warunków, zwłaszcza tych opartych na pojedynczej zmiennej lub wyrażeniu dopasowującym wzorzec. Zapewniają one bardziej przejrzystą i zrozumiałą składnię w porównaniu z instrukcjami if, co ma kluczowe znaczenie zarówno dla pisania, jak i utrzymywania kodu.

Podstawy instrukcji switch

Czym jest instrukcja switch?

Instrukcja switch w języku C# to struktura kontrolna służąca do wyboru jednej z wielu ścieżek kodu do wykonania. Wybór opiera się na wartości lub wyrażeniu. Jest to wydajna alternatywa dla stosowania wielu warunków if-else, zwłaszcza w przypadku zmiennej, która może przyjmować kilka różnych wartości.

Składnia

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.

Zrozumienie instrukcji break

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.

Porównanie instrukcji switch i if-else

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.

Przykład: użycie instrukcji switch

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

Zrozumienie przypadku default w bloku switch

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.

Jak i kiedy używać instrukcji default

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.

Przykład: instrukcja switch z przypadkiem default

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

Najlepsze praktyki dotyczące przypadku default

  • 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

Wprowadzenie do wyrażeń switch w 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.

Składnia wyrażeń switch

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.

Przykład: użycie wyrażenia switch

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.

Dopasowywanie wzorców z wyrażeniami switch

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

Instrukcja switch a wyrażenie switch w C

  • 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

Przykład: warunkowe znakowanie wodne z IronPDF i instrukcjami switch

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

Wnioski

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

Często Zadawane Pytania

Jak moge wykorzystac instrukcje switch do zarzadzania przetwarzaniem PDF w C#?

Mozesz wykorzystac instrukcje switch do zarzadzania przetwarzaniem PDF poprzez wykonywanie roznych operacji na PDF na podstawie warunkow, takich jak liczba stron lub typ dokumentu, korzystajac z biblioteki takiej jak IronPDF.

Jaka jest roznica miedzy instrukcja switch a wyrazeniem switch w C#?

Instrukcja switch zapewnia strukturalny sposob obslugi wielu warunkow z uzyciem instrukcji break, aby zapobiec przeskakiwaniu, podczas gdy wyrazenie switch jest bardziej zwiezle, zwraca wartosc i eliminuje potrzebe uzycia instrukcji break.

Dlaczego domyslna sprawa jest wazna w instrukcjach switch w C#?

Domyslna sprawa jest kluczowa, poniewaz zapewnia obsluge nieoczekiwanych wartosci, zapobiegajac bledom poprzez zapewnienie akcji awaryjnej, gdy zadna sprawa nie pasuje do wyrazenia.

Jak wyrazenia switch zwiekszaja czytelnosc kodu w C#?

Wyrazenia switch zwiekszaja czytelnosc kodu, oferujac zwiezla skladnie na potrzeby rozgalezien warunkowych, pozwalajac programistom na wyrazanie logiki w bardziej zwartej formie, co ulatwia zrozumienie i utrzymanie kodu.

Czy instrukcje switch moga byc uzywane do obslugi bledow w aplikacjach C#?

Tak, instrukcje switch moga byc uzywane do obslugi bledow, kierujac program do specyficznych procedur obslugi bledow na podstawie kodow bledow lub warunkow, co poprawia solidnosc aplikacji C#.

Jaki jest praktyczny przyklad uzycia instrukcji switch z IronPDF?

Praktyczny przyklad to uzycie instrukcji switch do zastosowania roznych znakow wodnych do dokumentu PDF na podstawie liczby stron lub innych kryteriow, korzystajac z IronPDF do zadan manipulacji PDF.

Jak IronPDF ulatwia operacje na PDF oparte na switch?

IronPDF ulatwia operacje na PDF oparte na switch, oferujac mocny zestaw narzedzi i metod, ktore moga byc uruchamiane warunkowo przy uzyciu instrukcji switch do zadan takich jak konwersja, edytowanie i renderowanie PDF.

Jakie sa niektore powszechne scenariusze uzycia instrukcji switch w przetwarzaniu PDF?

Powszechne scenariusze uzycia obejmuja stosowanie roznych zasad przetwarzania na podstawie metadanych dokumentu, takich jak stosowanie specyficznego formatowania lub konwersji na podstawie typu lub zawartosci dokumentu.

Jak IronPDF moze pomoc w tworzeniu czytelnego i latwego do utrzymania kodu z instrukcjami switch?

IronPDF pomaga oferujac kompleksowe metody manipulacji PDF, ktore moga byc zorganizowane za pomoca instrukcji switch, co skutkuje kodem czytelnym i latwym do utrzymania dzieki jego uporzadkowanej logice.

Jakie zalety oferuja instrukcje switch w porownaniu z blokami if-else w podejmowaniu decyzji?

Instrukcje switch oferuja bardziej uporzadkowana i mniej narazona na bledy strukture do obslugi wielu dyskretnych warunkow, zwiekszajac przejrzystosc kodu i zmniejszajac prawdopodobienstwo bledow w porownaniu z dlugimi lancuchami if-else.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie