bool (C# リファレンス)

bool キーワードは、System.Boolean のエイリアスです。 ブール値 (true および false) を格納する変数を宣言するときに使用します。

注意

null の値も受け取ることができるブール変数が必要な場合は、bool? を使用します。 詳細については、「null 許容型 (C# プログラミング ガイド)」を参照してください。

リテラル

bool 変数にはブール値を代入できます。 bool として評価される式を bool 変数に代入することもできます。

public class BoolTest
{
    static void Main()
    {
        bool b = true;

        // WriteLine automatically converts the value of b to text.
        Console.WriteLine(b);

        int days = DateTime.Now.DayOfYear;


        // Assign the result of a boolean expression to b.
        b = (days % 2 == 0);

        // Branch depending on whether b is true or false.
        if (b)
        {
            Console.WriteLine("days is an even number");
        }
        else
        {
            Console.WriteLine("days is an odd number");
        }   
    }
}
/* Output:
  True
  days is an <even/odd> number
*/

bool 変数の既定値は false です。 bool? 変数の既定値は null です。

変換

C++ では、bool 型の値を int 型の値に変換できます。つまり、false は 0 と等価であり、true は 0 以外の値と等価です。 C# では、bool 型とその他の型は変換できません。 たとえば、C# では次の if ステートメントは無効です。

int x = 123;

// if (x)   // Error: "Cannot implicitly convert type 'int' to 'bool'"
{
    Console.Write("The value of x is nonzero.");
}

int 型の変数をテストするには、次のように、明示的に特定の値 (たとえば 0) と比較する必要があります。


if (x != 0)   // The C# way
{
    Console.Write("The value of x is nonzero.");
}

使用例

ここでは、キーボードから文字が入力されると、入力文字がアルファベットかどうかをチェックするプログラムの例を示します。 アルファベットの場合は、大文字か小文字かをチェックします。 これらのチェックは、IsLetter および IsLower を使用して実行され、この両方が bool 型を返します。

public class BoolKeyTest
{
    static void Main()
    {
        Console.Write("Enter a character: ");
        char c = (char)Console.Read();
        if (Char.IsLetter(c))
        {
            if (Char.IsLower(c))
            {
                Console.WriteLine("The character is lowercase.");
            }
            else
            {
                Console.WriteLine("The character is uppercase.");
            }
        }
        else
        {
            Console.WriteLine("Not an alphabetic character.");
        }
    }
}
/* Sample Output:
    Enter a character: X
    The character is uppercase.

    Enter a character: x
    The character is lowercase.

    Enter a character: 2
    The character is not an alphabetic character.
 */

C# 言語仕様

詳細については、「C# 言語仕様」を参照してください。 言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。

参照

参照

C# のキーワード

整数型の一覧表 (C# リファレンス)

組み込み型の一覧表 (C# リファレンス)

暗黙的な数値変換の一覧表 (C# リファレンス)

明示的な数値変換の一覧表 (C# リファレンス)

概念

C# プログラミング ガイド

その他の技術情報

C# リファレンス