透かしなしで本番環境でテストしてください。
必要な場所で動作します。
30日間、完全に機能する製品をご利用いただけます。
数分で稼働させることができます。
製品トライアル期間中にサポートエンジニアリングチームへの完全アクセス
このチュートリアルでは、C#プログラムで効果的に使用するためのif
およびelse
文の概念を分かりやすく説明します。 関連する概念として、ブール式や条件演算子についても探っていきます。 それでは、早速始めましょう!
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
if文は、指定されたブール式がtrue
と評価されることを確認します。 もしそうであれば、ステートメントブロック内のコード(波括弧で囲まれたコード)が実行されます。 ブール式がfalse
に評価される場合、ステートメントブロック内のコードはスキップされます。
では、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
上記の場合、ブール式が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
上記のコードでは、最初に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
上記の例では、まず整数型の変数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
上記のコードでは、まずage
という名前の整数型変数とisStudent
という名前のブール型変数を宣言します。 次に、論理演算子を使ったif-else文を使って、その人が割引を受ける資格があるかどうかをチェックします。 年齢が65歳以上、または18歳から25歳の学生の場合、プログラムは「割引の対象です!」と表示します。それ以外の場合は、「申し訳ありませんが、割引の対象ではありません。」と表示します。
C#のif-else文についてしっかりと理解したところで、C#アプリケーションでPDFファイルをシームレスに扱えるIronPDFライブラリに関する実用的な応用を探ってみましょう。
IronPDFは、C#アプリケーション内でPDFファイルを作成、編集、内容を抽出することができる強力な.NETライブラリです。
この例では、顧客の所在地に基づいて異なる税率を適用するシンプルなPDF請求書ジェネレーターを作成します。 このシナリオは、if-else文を活用する絶好の機会となります。
まず、次のコマンドを実行してNuGetを介してIronPDFをインストールします:
Install-Package IronPdf
Install-Package IronPdf
次に、異なる地域の顧客に対して異なる税率で請求書を生成する簡単なプログラムを作成しましょう。
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
このコード例では、if-else文を使用して、顧客の所在地に基づいて適切な税率を決定します。 私たちはIronPDFを使用してHTML文字列からPDF請求書を作成します。 C#では、C# Listを使用してアイテムを保存および操作することができ、例えば製品の価格を扱います。
このチュートリアルでは、C#のif-else文の基本を説明し、さまざまな条件演算子や論理演算子を調べ、実際の例を検証して、概念の理解を深めました。 私たちは、強力なIronPDFライブラリを使用した実用的なアプリケーションも実演しました。このライブラリは無料トライアルとライセンスオプションを提供しています。
プログラミングの概念を習得するには、練習が重要であることを忘れないでください。if-else文やその他の関連概念に関する新しい知識を応用しながら、さまざまなシナリオで実験を続けてください。