フッターコンテンツにスキップ
.NETヘルプ

C# If (開発者向けの仕組み)

このチュートリアルでは、ifステートメントとelseステートメントの概念を分解し、C#プログラムでそれらを効果的に使用する方法を説明します。 また、ブール式や条件演算子といった関連する概念も探索します。 それでは、さっそく始めましょう!

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条件が偽のときに他のコードを実行したい場合はどうしますか? そのときに使うのが、オプションの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以上であるかを確認します。条件がtrueであれば、「You are eligible to vote!」がコンソールに表示されます。 falseの場合、「Sorry, you are not eligible to vote.」が表示されます。

ブール式の操作

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

  • ||:論理OR==`**:等しい
  • ||:論理OR!=`**:等しくない
  • ||:論理OR<`**:より小さい
  • ||:論理OR>`**:より大きい
  • ||:論理OR<=`**:以下
  • ||:論理OR>=`**:以上

例を見てみましょう。 正負やゼロをチェックするプログラムを書きたいとします。 このコードスニペットは、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より大きいかどうかを確認します。trueであれば、「The number is positive.」を印刷します。falseの場合は、次のelse ifステートメントに進み、数値が0より小さいかどうかを確認します。この条件がtrueであれば、「The number is negative.」を印刷します。最後に、どの条件にも当てはまらない場合、elseブロックに達し、「The number is zero.」を印刷します。

論理演算子を使用して条件を結合する

場合によっては、一度に複数の条件を確認する必要があるかもしれません。 C#では、これを達成するための論理演算子が用意されています。 最も一般的に使用される論理演算子は次の通りです:

  • ||:論理OR&&`**:論理AND
  • ||:論理OR||* !:論理NOT
  • ||:論理OR!`**: Logical NOT

店舗で特別割引を受ける資格があるかを判断するプログラムを書いているとします。 割引は高齢者(65歳以上)、または学生(18歳から25歳まで)に利用できます。 次のコードスニペットは、C#のif-elseステートメントと論理演算子を使用して割引資格を判断する方法を示しています: 上記のコードでは、まずageという整数変数とisStudentというブール変数を宣言します。

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

次に、if-elseステートメントと論理演算子を使用して、その人が割引を受ける資格があるかを確認します。 年齢が65歳以上であるか、または18歳から25歳までの学生である場合、プログラムは「You are eligible for the discount!」を印刷します。それ以外の場合、「Sorry, you are not eligible for the discount.」を印刷します。 ## IronPDFを使ったPDFの生成:If-Elseステートメントの関連アプリケーション

C#のif-elseステートメントをしっかりと理解した今、IronPDFライブラリ、C#アプリケーションでPDFファイルをシームレスに操作できるライブラリを利用し、実用的なアプリケーションを探ってみましょう。

IronPDFは、C#アプリケーション内でPDFファイルの作成、編集、および抽出を可能にする強力な.NETライブラリです。

この例では、顧客の所在地に基づいて異なる税率を適用する簡単なPDF請求書生成プログラムを作成します。

このシナリオは、if-elseステートメントを利用する絶好の機会です。 まず、次のコマンドでIronPDFをNuGetを介してインストールします。

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

Install-Package IronPdf

このコード例では、顧客の所在地に基づいて適切な税率を決定するためにif-elseステートメントを使用します。

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

IronPDFを使用してHTML文字列からPDF請求書を作成します。 C#では、C#リストを利用して、商品価格などのアイテムを格納および操作できます。 C# If (開発者のための動作) 図1

このチュートリアルを通して、C#のif-elseステートメントの基本を説明し、さまざまな条件および論理演算子を探索し、現実の例を調査して概念をよりよく理解しました。

結論

強力な無料トライアルとライセンスオプションが利用可能です。 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文は、指定されたブール条件がtrueと評価されるときにのみコードブロックを実行するために使用されます。これはプログラム内での意思決定に不可欠です。

if-else文はC#プログラミングをどのように強化しますか?

C#のif-else文は、条件が真か偽かに基づいて異なるコードブロックを実行することを可能にし、プログラミングにおけるさまざまな論理シナリオを処理するために重要です。

ブール式はC#の条件文でどのような役割を果たしますか?

ブール式はC#の条件文で重要な役割を果たし、ifやif-else構造内での実行フローを制御する真偽値を決定します。

C#で一般的に使用される条件演算子はどれですか?

C#で一般的な条件演算子には、'==', '!=', '<', '>', '<=', '>='があります。これらの演算子はif文内で条件を評価するために使用されます。

C#でif文とともに論理演算子をどのように利用できますか?

論理演算子の'&&'(AND)、'||'(OR)、'!'(NOT)は、複数の条件を組み合わせるためにif文内で使用でき、C#で複雑なロジックを評価することを可能にします。

C#によるPDF生成で条件ロジックをどのように適用できますか?

条件ロジックはif-else文でPDF生成に使用され、特定の条件に基づいて異なる形式や内容を適用し、動的なドキュメント作成を可能にします。

if-else文を論理演算子とともに使用する例を教えてください。

論理演算子を使用したif-else文の例としては、高齢者や学生としての資格を持つかどうかの年齢基準に基づいた割引資格をチェックすることがあります。

C#でif-else文を実践する実用的な方法は何ですか?

if-else文を実践する一つの方法は、意思決定ロジックを含む小さなプログラムを作成することで、例えば年齢に基づいて投票資格を判断することです。

PDF請求書ジェネレーターで税率を管理するためにif-else文をどのように使用できますか?

PDF請求書ジェネレーターでは、if-else文を使用して、場所や顧客の種類などの条件に基づいて異なる税率を適用し、請求書の正確性と機能を向上させます。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。