Zum Fußzeileninhalt springen
.NET HILFE

C# Wenn (Wie es für Entwickler funktioniert)

In this tutorial, we'll break down the concepts of if and else statements, and how to use them effectively in your C# programs. We'll also explore related concepts such as Boolean expressions and conditional operators. So, let's dive right in!

Understanding the If Statement

The if statement is a fundamental concept in programming. It is used to make decisions in code based on a certain condition. The basic syntax of an if statement in C# is as follows:

if (Boolean expression)
{
    // Statements to execute if the Boolean expression is true
}
if (Boolean expression)
{
    // Statements to execute if the Boolean expression is true
}
If Boolean expression Then
	' Statements to execute if the Boolean expression is true
End If
$vbLabelText   $csharpLabel

The if statement checks that the given Boolean expression evaluates to true. If it does, the code inside the statement block (the code enclosed in the curly braces) is executed. If the Boolean expression evaluates to false, the code inside the statement block is skipped.

The Power of the If-Else Statement

Now, what if you want to execute some other code when the if condition is false? That's where the optional else statement comes into play. The syntax for an if-else statement in C# looks like this:

if (Boolean expression)
{
    // Statements to execute if the Boolean expression is true
}
else
{
    // Statements to execute if the Boolean expression is false
}
if (Boolean expression)
{
    // Statements to execute if the Boolean expression is true
}
else
{
    // Statements to execute if the Boolean expression is false
}
If Boolean expression Then
	' Statements to execute if the Boolean expression is true
Else
	' Statements to execute if the Boolean expression is false
End If
$vbLabelText   $csharpLabel

In the above case, if the Boolean expression evaluates to true, the code in the if block is executed. If it evaluates to false, the code in the else block is executed instead.

A Simple Example

Let's see a real-life example of using the C# if-else statement. Imagine you're writing a program that checks if a person is eligible to vote. In most countries, the voting age is 18.

The following example demonstrates how to use the if-else statement to determine voting eligibility:

using System;

class Program
{
    static void Main(string[] args)
    {
        int age = 21;

        if (age >= 18)
        {
            Console.WriteLine("You are eligible to vote!");
        }
        else
        {
            Console.WriteLine("Sorry, you are not eligible to vote.");
        }
    }
}
using System;

class Program
{
    static void Main(string[] args)
    {
        int age = 21;

        if (age >= 18)
        {
            Console.WriteLine("You are eligible to vote!");
        }
        else
        {
            Console.WriteLine("Sorry, you are not eligible to vote.");
        }
    }
}
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim age As Integer = 21

		If age >= 18 Then
			Console.WriteLine("You are eligible to vote!")
		Else
			Console.WriteLine("Sorry, you are not eligible to vote.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, we first declare an integer variable named age and assign it the value of 21. Then, we use an if-else statement to check if the age is greater than or equal to 18. If the condition is true, the program prints "You are eligible to vote!" to the console. If it's false, it prints "Sorry, you are not eligible to vote."

Working with Boolean Expressions

In C#, you can use various types of Boolean expressions to create more complex conditions. Some commonly used conditional operators include:

  • ==: Equality
  • !=: Inequality
  • <: Less than
  • >: Greater than
  • <=: Less than or equal to
  • >=: Greater than or equal to

Let's take a look at an example. Suppose you want to write a program that checks if a number is positive, negative, or zero. The following code snippet uses if statements and conditional operators to achieve this:

using System;

class Program
{
    static void Main(string[] args)
    {
        int number = 0;

        if (number > 0)
        {
            Console.WriteLine("The number is positive.");
        }
        else if (number < 0)
        {
            Console.WriteLine("The number is negative.");
        }
        else
        {
            Console.WriteLine("The number is zero.");
        }
    }
}
using System;

class Program
{
    static void Main(string[] args)
    {
        int number = 0;

        if (number > 0)
        {
            Console.WriteLine("The number is positive.");
        }
        else if (number < 0)
        {
            Console.WriteLine("The number is negative.");
        }
        else
        {
            Console.WriteLine("The number is zero.");
        }
    }
}
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim number As Integer = 0

		If number > 0 Then
			Console.WriteLine("The number is positive.")
		ElseIf number < 0 Then
			Console.WriteLine("The number is negative.")
		Else
			Console.WriteLine("The number is zero.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above example, we first declare an integer variable named number and assign it the value of 0. We then use an if statement to check if the number is greater than 0. For a true value, we print "The number is positive." For false values, we move on to the else if statement, which checks if the number is less than 0. If this condition is true, we print "The number is negative." Finally, if none of the previous conditions are met, we reach the else block, which prints "The number is zero."

Combining Conditions with Logical Operators

In some cases, you might need to check multiple conditions at once. C# provides logical operators to help you achieve this. The most commonly used logical operators are:

  • &&: Logical AND
  • ||: Logical OR
  • !: Logical NOT

Let's see an example of using logical operators with if statements. Imagine you're writing a program to determine if a person qualifies for a special discount at a store. The discount is available to customers who are either senior citizens (age 65 or older) or students (age between 18 and 25). Here's a code snippet that demonstrates how to use the C# if-else statement with logical operators to determine discount eligibility:

using System;

class Program
{
    static void Main(string[] args)
    {
        int age = 23;
        bool isStudent = true;

        if ((age >= 65) || (isStudent && (age >= 18 && age <= 25)))
        {
            Console.WriteLine("You are eligible for the discount!");
        }
        else
        {
            Console.WriteLine("Sorry, you are not eligible for the discount.");
        }
    }
}
using System;

class Program
{
    static void Main(string[] args)
    {
        int age = 23;
        bool isStudent = true;

        if ((age >= 65) || (isStudent && (age >= 18 && age <= 25)))
        {
            Console.WriteLine("You are eligible for the discount!");
        }
        else
        {
            Console.WriteLine("Sorry, you are not eligible for the discount.");
        }
    }
}
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim age As Integer = 23
		Dim isStudent As Boolean = True

		If (age >= 65) OrElse (isStudent AndAlso (age >= 18 AndAlso age <= 25)) Then
			Console.WriteLine("You are eligible for the discount!")
		Else
			Console.WriteLine("Sorry, you are not eligible for the discount.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, we first declare an integer variable named age and a Boolean variable named isStudent. We then use an if-else statement with logical operators to check if the person qualifies for the discount. If the age is 65 or older, or if the person is a student between 18 and 25, the program prints "You are eligible for the discount!" Otherwise, it prints "Sorry, you are not eligible for the discount."

Generating PDFs with IronPDF: A Relevant Application of If-Else Statements

Now that you have a solid grasp on the C# if-else statement, let's explore a practical application involving the IronPDF library, which allows you to work with PDF files in C# applications seamlessly.

IronPDF is a powerful .NET library that allows you to create, edit, and extract content from PDF files within your C# applications.

In this example, we will create a simple PDF invoice generator that applies different tax rates based on the customer's location. This scenario provides an excellent opportunity to utilize if-else statements.

First, install IronPDF via NuGet by running the following command:

Install-Package IronPdf

Next, let's create a simple program that generates an invoice with different tax rates for customers in different regions:

using System;
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        string customerLocation = "Europe";
        double taxRate;

        // Determine tax rate based on customer location
        if (customerLocation == "USA")
        {
            taxRate = 0.07;
        }
        else if (customerLocation == "Europe")
        {
            taxRate = 0.20;
        }
        else
        {
            taxRate = 0.15;
        }

        double productPrice = 100.0;
        double totalTax = productPrice * taxRate;
        double totalPrice = productPrice + totalTax;

        string invoiceContent = $@"
            <h1>Invoice</h1>
            <p>Product Price: ${productPrice}</p>
            <p>Tax Rate: {taxRate * 100}%</p>
            <p>Total Tax: ${totalTax}</p>
            <p>Total Price: ${totalPrice}</p>
        ";

        // Render the HTML content to a PDF document using IronPDF
        var pdf = new ChromePdfRenderer();
        var document = pdf.RenderHtmlAsPdf(invoiceContent);
        document.SaveAs("Invoice.pdf"); // Save the PDF file locally
    }
}
using System;
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        string customerLocation = "Europe";
        double taxRate;

        // Determine tax rate based on customer location
        if (customerLocation == "USA")
        {
            taxRate = 0.07;
        }
        else if (customerLocation == "Europe")
        {
            taxRate = 0.20;
        }
        else
        {
            taxRate = 0.15;
        }

        double productPrice = 100.0;
        double totalTax = productPrice * taxRate;
        double totalPrice = productPrice + totalTax;

        string invoiceContent = $@"
            <h1>Invoice</h1>
            <p>Product Price: ${productPrice}</p>
            <p>Tax Rate: {taxRate * 100}%</p>
            <p>Total Tax: ${totalTax}</p>
            <p>Total Price: ${totalPrice}</p>
        ";

        // Render the HTML content to a PDF document using IronPDF
        var pdf = new ChromePdfRenderer();
        var document = pdf.RenderHtmlAsPdf(invoiceContent);
        document.SaveAs("Invoice.pdf"); // Save the PDF file locally
    }
}
Imports System
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim customerLocation As String = "Europe"
		Dim taxRate As Double

		' Determine tax rate based on customer location
		If customerLocation = "USA" Then
			taxRate = 0.07
		ElseIf customerLocation = "Europe" Then
			taxRate = 0.20
		Else
			taxRate = 0.15
		End If

		Dim productPrice As Double = 100.0
		Dim totalTax As Double = productPrice * taxRate
		Dim totalPrice As Double = productPrice + totalTax

		Dim invoiceContent As String = $"
            <h1>Invoice</h1>
            <p>Product Price: ${productPrice}</p>
            <p>Tax Rate: {taxRate * 100}%</p>
            <p>Total Tax: ${totalTax}</p>
            <p>Total Price: ${totalPrice}</p>
        "

		' Render the HTML content to a PDF document using IronPDF
		Dim pdf = New ChromePdfRenderer()
		Dim document = pdf.RenderHtmlAsPdf(invoiceContent)
		document.SaveAs("Invoice.pdf") ' Save the PDF file locally
	End Sub
End Class
$vbLabelText   $csharpLabel

In this code example, we use an if-else statement to determine the appropriate tax rate based on the customer's location. We create the PDF invoice from HTML string using IronPDF. In C#, we can utilize a C# List to store and manipulate items, such as product prices.

C# If (How It Works For Developers) Figure 1

Conclusion

Throughout this tutorial, we've covered the fundamentals of the C# if-else statement, explored various conditional and logical operators, and examined real-life examples to better understand the concept. We even demonstrated a practical application using the powerful IronPDF library, which offers a free trial and licensing options.

Remember, practice is crucial when it comes to mastering programming concepts. Keep experimenting with different scenarios, applying your newfound knowledge of if-else statements and other related concepts.

Häufig gestellte Fragen

Was ist der Zweck einer If-Anweisung in C#?

Eine If-Anweisung in C# wird verwendet, um einen Codeblock nur dann auszuführen, wenn eine bestimmte boolesche Bedingung als wahr bewertet wird. Dies ist unerlässlich für Entscheidungen in Ihrem Programm.

Wie verbessern If-Else-Anweisungen die Programmierung in C#?

If-Else-Anweisungen in C# ermöglichen es Programmierern, unterschiedliche Codeblöcke basierend darauf auszuführen, ob eine Bedingung wahr oder falsch ist, was entscheidend für die Handhabung verschiedener logischer Szenarien in der Programmierung ist.

Welche Rolle spielen boolesche Ausdrücke in C#-Bedingungen?

Boolesche Ausdrücke sind entscheidend in C#-Bedingungen, da sie den Wahrheitswert bestimmen, der den Ablauf der Ausführung in If- und If-Else-Konstrukten steuert.

Welche Bedingungsoperatoren werden häufig in C# verwendet?

Häufig verwendete Bedingungsoperatoren in C# sind '==', '!=', '<', '>', '<=' und '>='. Diese Operatoren werden verwendet, um Bedingungen innerhalb von If-Anweisungen zu bewerten.

Wie können logische Operatoren mit If-Anweisungen in C# genutzt werden?

Logische Operatoren wie '&&' (UND), '||' (ODER) und '!' (NICHT) können innerhalb von If-Anweisungen verwendet werden, um mehrere Bedingungen zu kombinieren, was die Bewertung komplexer Logik in C# ermöglicht.

Wie kann bedingte Logik bei der PDF-Erstellung mit C# angewendet werden?

Bedingte Logik mit If-Else-Anweisungen kann bei der PDF-Erstellung verwendet werden, um basierend auf spezifischen Bedingungen unterschiedliche Formate oder Inhalte anzuwenden, was eine dynamische Dokumenterstellung ermöglicht.

Können Sie ein Beispiel für die Verwendung von If-Else-Anweisungen mit logischen Operatoren geben?

Ein Beispiel für die Verwendung von If-Else-Anweisungen mit logischen Operatoren ist die Überprüfung der Rabattberechtigung basierend auf Alterskriterien, wie z.B. als Senior oder Student zu qualifizieren.

Wie kann man If-Else-Anweisungen in C# praktisch üben?

Eine praktische Möglichkeit zum Üben von If-Else-Anweisungen besteht darin, kleine Programme zu erstellen, die Entscheidungslogik beinhalten, wie z.B. die Bestimmung der Wahlberechtigung basierend auf dem Alter.

Wie können If-Else-Anweisungen Steuersätze in einem PDF-Rechnungsgenerator verwalten?

In einem PDF-Rechnungsgenerator können If-Else-Anweisungen verwendet werden, um unterschiedliche Steuersätze basierend auf Bedingungen wie Standort oder Kundentyp anzuwenden, was die Genauigkeit und Funktionalität der Rechnungen verbessert.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen