푸터 콘텐츠로 바로가기
.NET 도움말

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.

자주 묻는 질문

C#에서 if 문의 목적은 무엇인가요?

C#의 if 문은 지정된 부울 조건이 참으로 평가될 때만 코드 블록을 실행하는 데 사용됩니다. 이는 프로그램에서 의사 결정을 내리는 데 필수적입니다.

If-else 문은 C# 프로그래밍을 어떻게 향상시킬 수 있나요?

프로그래머는 C#의 If-else 문을 사용하여 조건이 참인지 거짓인지에 따라 다양한 코드 블록을 실행할 수 있으며, 이는 프로그래밍에서 다양한 논리 시나리오를 처리하는 데 매우 중요합니다.

C# 조건문에서 부울 표현식은 어떤 역할을 하나요?

부울 표현식은 if 및 if-else 구문에서 실행 흐름을 제어하는 진리 값을 결정하기 때문에 C# 조건문에서 매우 중요합니다.

C#에서 일반적으로 사용되는 조건 연산자는 무엇인가요?

C#의 일반적인 조건 연산자에는 '==', '!=', '<', '>', '<=' 및 '>=' 등이 있습니다. 이러한 연산자는 if 문 내에서 조건을 평가하는 데 사용됩니다.

논리 연산자는 C#의 if 문에서 어떻게 활용될 수 있나요?

'&&'(AND), '||'(OR), '!'(NOT) 등의 논리 연산자는 if 문 내에서 여러 조건을 결합하는 데 사용할 수 있으므로 C#에서 복잡한 논리를 평가할 수 있습니다.

C#으로 PDF 생성에 조건부 논리를 어떻게 적용할 수 있나요?

PDF 생성 시 if-else 문이 포함된 조건부 논리를 사용하여 특정 조건에 따라 다른 형식이나 콘텐츠를 적용할 수 있으므로 동적인 문서 생성이 가능합니다.

논리 연산자와 함께 if-else 문을 사용하는 예를 들어 설명할 수 있나요?

논리 연산자와 함께 if-else 문을 사용하는 예로는 고령자 또는 학생 자격과 같은 연령 기준에 따라 할인 자격을 확인하는 경우를 들 수 있습니다.

C#에서 if-else 문을 사용하는 실용적인 연습 방법은 무엇인가요?

만약 문장을 연습하는 한 가지 실용적인 방법은 나이에 따른 투표 자격 결정과 같은 의사 결정 로직이 포함된 작은 프로그램을 만드는 것입니다.

PDF 인보이스 생성기에서 if-else 문으로 세율을 어떻게 관리할 수 있나요?

PDF 송장 생성기에서 if-else 문은 위치 또는 고객 유형과 같은 조건에 따라 다른 세율을 적용하여 송장의 정확성과 기능을 향상시키는 데 사용할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.