C# Learner,
I'm a bit baffled by this:
Console.WriteLine(true | false);
Surely that's binary, not logical, OR... right?
And then there's this:
Console.WriteLine(true || false);
From the MSDN help:
----------------------------------------------------------------------------
--
Binary | operators are predefined for the integral types and bool. For
integral types, | computes the bitwise OR of its operands. For bool
operands, | computes the logical OR of its operands; that is, the result is
false if and only if both its operands are false.
expr1 | expr2
Where: expr1 -- An expression.
expr2 -- An expression.
// cs_operator_OR.cs
using System;
class Test
{
public static void Main()
{
Console.WriteLine(true | false); // logical or
Console.WriteLine(false | false); // logical or
Console.WriteLine("0x{0:x}", 0xf8 | 0x3f); // bitwise or
}
}
Output:
True
False
0xff
----------------------------------------------------------------------------
--
and
----------------------------------------------------------------------------
--
The conditional-OR operator (||) performs a logical-OR of its bool operands,
but only evaluates its second operand if necessary.
expr1 || expr2
Where: expr1 -- An expression.
expr2 -- An expression.
// cs_operator_short_circuit_OR.cs
using System;
class Test
{
static bool fn1()
{
Console.WriteLine("fn1 called");
return true;
}
static bool fn2()
{
Console.WriteLine("fn2 called");
return false;
}
public static void Main()
{
Console.WriteLine("regular OR:");
Console.WriteLine("result is {0}", fn1() | fn2());
Console.WriteLine("short-circuit OR:");
Console.WriteLine("result is {0}", fn1() || fn2());
}
}
Output:
regular OR:
fn1 called
fn2 called
result is True
short-circuit OR:
fn1 called
result is True
-------------------------------------------------------------------
I hope that helps clear things up and doesn't get me into too much trouble
with the copyright people.
Regards,
Randy