Share via


&& 演算子 (C# リファレンス)

条件 AND 演算子 (&&) では bool オペランドの論理 AND が実行されますが、必要な場合のみ、2 番目のオペランドが評価されます。

解説

x && y

この演算は次の演算に相当します。

x & y

ただしx が false 場合y は y の値と演算結果が false であるためは評価されません。 これは、"ショートサーキット" 評価と呼ばれます。

条件 AND 演算子はオーバーロードできませんが、通常の論理演算子および true 演算子と false 演算子のオーバーロードは、条件論理演算子の制約付きのオーバーロードとも見なされます。

使用例

次の例ではif の 2 番目のステートメントの条件式はオペランドが false を返すため1 番目のオペランドだけが評価されます。

class LogicalAnd
{
    static void Main()
    {
        // Each method displays a message and returns a Boolean value.  
        // Method1 returns false and Method2 returns true. When & is used, 
        // both methods are called. 
        Console.WriteLine("Regular AND:");
        if (Method1() & Method2())
            Console.WriteLine("Both methods returned true.");
        else
            Console.WriteLine("At least one of the methods returned false.");

        // When && is used, after Method1 returns false, Method2 is  
        // not called.
        Console.WriteLine("\nShort-circuit AND:");
        if (Method1() && Method2())
            Console.WriteLine("Both methods returned true.");
        else
            Console.WriteLine("At least one of the methods returned false.");
    }

    static bool Method1()
    {
        Console.WriteLine("Method1 called.");
        return false;
    }

    static bool Method2()
    {
        Console.WriteLine("Method2 called.");
        return true;
    }
}
// Output: 
// Regular AND: 
// Method1 called. 
// Method2 called. 
// At least one of the methods returned false. 

// Short-circuit AND: 
// Method1 called. 
// At least one of the methods returned false.

C# 言語仕様

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

参照

関連項目

C# 演算子

概念

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

その他の技術情報

C# リファレンス