Skip to footer content
.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
}
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.

Frequently Asked Questions

What is the purpose of an if statement in C#?

An if statement in C# is used to execute a block of code only when a specified Boolean condition evaluates to true. This is essential for making decisions in your program.

How do if-else statements enhance C# programming?

If-else statements in C# allow programmers to execute different blocks of code based on whether a condition is true or false, which is critical for handling various logical scenarios in programming.

What role do Boolean expressions play in C# conditional statements?

Boolean expressions are crucial in C# conditional statements because they determine the truth value that controls the flow of execution in if and if-else constructs.

Which conditional operators are commonly used in C#?

Common conditional operators in C# include '==', '!=', '<', '>', '<=', and '>='. These operators are used to evaluate conditions within if statements.

How can logical operators be utilized with if statements in C#?

Logical operators such as '&&' (AND), '||' (OR), and '!' (NOT) can be used within if statements to combine multiple conditions, allowing for the evaluation of complex logic in C#.

How can conditional logic be applied in PDF generation with C#?

Conditional logic with if-else statements can be used in PDF generation to apply different formats or content based on specific conditions, enabling dynamic document creation.

Can you give an example of using if-else statements with logical operators?

An example of using if-else statements with logical operators is checking for discount eligibility based on age criteria, such as qualifying as a senior citizen or a student.

What is a practical way to practice using if-else statements in C#?

One practical way to practice if-else statements is by creating small programs that involve decision-making logic, such as determining voting eligibility based on age.

How can if-else statements manage tax rates in a PDF invoice generator?

In a PDF invoice generator, if-else statements can be used to apply different tax rates based on conditions such as location or customer type, enhancing the accuracy and functionality of the invoices.

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 ...Read More