.NET HELP

C# If (How it Works for Developers)

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

Frequently Asked Questions

What is an if statement in C#?

An if statement in C# is used to make decisions in code based on a certain condition. If the condition evaluates to true, the code inside the statement block is executed.

How does an if-else statement work in C#?

An if-else statement in C# allows you to execute one block of code if a condition is true, and a different block of code if the condition is false.

What are Boolean expressions in C#?

Boolean expressions in C# are expressions that evaluate to a Boolean value: true or false. They are used in conditional statements like if and if-else.

What are some common conditional operators in C#?

Common conditional operators in C# include '==', '!=', '<', '>', '<=', and '>='. These operators are used to compare values.

How can logical operators be combined with if statements?

Logical operators like '&&' (AND), '||' (OR), and '!' (NOT) can be used to combine multiple conditions in an if statement to evaluate complex logic.

Can you provide an example of using an if-else statement in a practical scenario?

A practical example of using an if-else statement is determining voting eligibility. By checking if a person's age is 18 or older, the program decides whether they can vote.

How can if-else statements be applied in generating PDFs with IronPDF?

If-else statements can be used with IronPDF to apply different tax rates in a PDF invoice based on customer location, demonstrating conditional logic in document generation.

What is a simple example of using if-else with logical operators?

An example is determining discount eligibility. A person qualifies if they are a senior citizen (age 65+) or a student (age 18-25), using logical operators to combine these conditions.

What are some ways to practice if-else statements in C#?

To practice if-else statements, one can experiment with different scenarios and conditions, such as building small programs that require decision-making logic.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
< PREVIOUS
C# Multiline String (How it Works for Developers)
NEXT >
Install NuGet Powershell (How it Works for Developers Tutorial)