.NET ヘルプ

C# If(開発者向けの動作説明)

このチュートリアルでは、C#プログラムで効果的に使用するためのifおよびelse文の概念を分かりやすく説明します。 関連する概念として、ブール式や条件演算子についても探っていきます。 それでは、早速始めましょう!

If文の理解

if ステートメントはプログラミングにおける基本的な概念です。 コード内で特定の条件に基づいて判断を行うために使用されます。 C#のif文の基本構文は以下の通りです:

    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

if文は、指定されたブール式がtrueと評価されることを確認します。 もしそうであれば、ステートメントブロック内のコード(波括弧で囲まれたコード)が実行されます。 ブール式がfalseに評価される場合、ステートメントブロック内のコードはスキップされます。

If-Else文の威力

では、if条件がfalseの場合に他のコードを実行したい場合はどうしますか? そこでオプションのelseステートメントが登場します。 C# におけるif-else文の構文は次のようになります:

    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

上記の場合、ブール式がtrueと評価されると、ifブロック内のコードが実行されます。 それがfalseと評価される場合、代わりにelseブロックのコードが実行されます。

簡単な例

C#のif-else文の実際の使用例を見てみましょう。 プログラムを作成して、ある人が投票する資格があるかどうかを確認することを想像してください。 ほとんどの国では、投票年齢は18歳です。

次の例は、投票資格を決定するために if-else 文を使用する方法を示しています:

    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

上記のコードでは、最初にageという名前の整数変数を宣言し、21という値を代入します。次に、if-else文を使用して、年齢が18以上であるかどうかを確認します。この条件が真である場合、プログラムはコンソールに「You are eligible to vote!」と出力します。 それが false の場合は、「申し訳ありませんが、投票資格がありません。」と表示されます。

ブール式の操作

C#では、より複雑な条件を作成するためにさまざまな種類のブール式を使用できます。 一般的に使用される条件演算子には、以下のものがあります:

  • ==: 等価性
  • !=: 不等式
  • <: 未満
  • >: より大きい
  • <=: 以下
  • >=: 大なりイコール

    例を見てみましょう。 もし、数値が正の数、負の数、またはゼロであるかどうかをチェックするプログラムを書きたい場合。 以下のコードスニペットは、if文と条件演算子を使用してこれを達成します:

    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

上記の例では、まず整数型の変数numberを宣言し、0の値を代入します。次に、if文を使用してその数が0より大きいかどうかを確認します。条件が真の場合、「The number is positive.」を出力します。条件が偽の場合、else if文に進み、数が0より小さいかどうかを確認します。この条件が真であれば、「The number is negative.」を出力します。最後に、前述のいずれの条件にも該当しない場合、elseブロックに達し、「The number is zero.」を出力します。

論理演算子を使用した条件の結合

場合によっては、複数の条件を同時に確認する必要があるかもしれません。 C#はこれを実現するための論理演算子を提供します。 最も一般的に使用される論理演算子は以下のとおりです:

  • &&: 論理積 (AND)
  • **`

    **: 論理和

  • !: 論理否定

    論理演算子をif文と共に使用する例を見てみましょう。 特定のストアで特別割引を受ける資格があるかどうかを判定するプログラムを作成すると仮定します。 この割引は、高齢者(65歳以上)または学生(18歳から25歳まで)のお客様が利用できます。 以下は、C#のif-else文と論理演算子を使用して割引の適格性を判断する方法を示すコードスニペットです:

    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)(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

上記のコードでは、まずageという名前の整数型変数とisStudentという名前のブール型変数を宣言します。 次に、論理演算子を使ったif-else文を使って、その人が割引を受ける資格があるかどうかをチェックします。 年齢が65歳以上、または18歳から25歳の学生の場合、プログラムは「割引の対象です!」と表示します。それ以外の場合は、「申し訳ありませんが、割引の対象ではありません。」と表示します。

IronPDFでPDFを生成する:If-Else文の関連アプリケーション

C#のif-else文についてしっかりと理解したところで、C#アプリケーションでPDFファイルをシームレスに扱えるIronPDFライブラリに関する実用的な応用を探ってみましょう。

IronPDFは、C#アプリケーション内でPDFファイルを作成、編集、内容を抽出することができる強力な.NETライブラリです。

この例では、顧客の所在地に基づいて異なる税率を適用するシンプルなPDF請求書ジェネレーターを作成します。 このシナリオは、if-else文を活用する絶好の機会となります。

まず、次のコマンドを実行してNuGetを介してIronPDFをインストールします:

Install-Package IronPdf
Install-Package IronPdf
SHELL

次に、異なる地域の顧客に対して異なる税率で請求書を生成する簡単なプログラムを作成しましょう。

    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
$vbLabelText   $csharpLabel

このコード例では、if-else文を使用して、顧客の所在地に基づいて適切な税率を決定します。 私たちはIronPDFを使用してHTML文字列からPDF請求書を作成します。 C#では、C# Listを使用してアイテムを保存および操作することができ、例えば製品の価格を扱います。

C# の If (開発者向けの作動方法) 図1

結論

このチュートリアルでは、C#のif-else文の基本を説明し、さまざまな条件演算子や論理演算子を調べ、実際の例を検証して、概念の理解を深めました。 私たちは、強力なIronPDFライブラリを使用した実用的なアプリケーションも実演しました。このライブラリは無料トライアルとライセンスオプションを提供しています。

プログラミングの概念を習得するには、練習が重要であることを忘れないでください。if-else文やその他の関連概念に関する新しい知識を応用しながら、さまざまなシナリオで実験を続けてください。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
C# マルチライン文字列 (開発者向けの仕組み)
次へ >
NuGet PowerShellのインストール(開発者向けチュートリアルの作業方法)