.NET HELP

C# If (How it Works for Developers)

Published May 23, 2023
Share:

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

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

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

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

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

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;

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

            var pdf = new ChromePdfRenderer();
            var document = pdf.RenderHtmlAsPdf(invoiceContent);
            document.SaveAs("Invoice.pdf");
        }
    }
    using System;
    using IronPdf;

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

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

            var pdf = new ChromePdfRenderer();
            var document = pdf.RenderHtmlAsPdf(invoiceContent);
            document.SaveAs("Invoice.pdf");
        }
    }
Imports System
	Imports IronPdf

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

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

			Dim pdf = New ChromePdfRenderer()
			Dim document = pdf.RenderHtmlAsPdf(invoiceContent)
			document.SaveAs("Invoice.pdf")
		End Sub
	End Class
VB   C#

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.

< PREVIOUS
C# Multiline String (How it Works for Developers)
NEXT >
Install NuGet Powershell (How it Works for Developers Tutorial)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,781,565 View Licenses >