Difference between & and && or | and || in c#

Logic

We know that a single | or & is a bitwise comparison.The double || or && is a logical comparison. More than this, these operators have another meaning.

&& or || Known as short-circuit-AND/OR logical operator
& or | Known as regular-AND/OR operator

Short-circuit-AND/OR logical operator
The && and || operators, which are the short-circuiting logical operators, are only defined for the type Boolean. Because of their short circuiting behavior, the second operand is not evaluated at run time if the operator result is known after evaluating the first operand.
The short-circuiting logical operators are evaluated as follows:
x && y
If the first operand in an && operation evaluates to False, the expression returns False. (because the result of the AND operation is false no matter what the value of y may be). Otherwise, the second operand is evaluated and a logical And operation is performed on the two results.
x || y
If the first operand in an || operation evaluates to True, the expression returns True. (because the result of the OR operation is false no matter what the value of y may be). Otherwise, the second operand is evaluated and a logical Or operation is performed on its two results.
When evaluating the && or || operators, the first operand is evaluated only once, and the second operand is either not evaluated or evaluated exactly once.

Regular-AND/OR operator
‘&’ and ‘|’ are more common for them to be used as bitwise operators, but can also be used as logical operators though. When they’re used as logical operators, both operands are always evaluated.

For example, consider the following code:

// cs_operator_logical_and.cs
 using System;
 class Test
 {
 static bool fn1()
 {
 Console.WriteLine("fn1 is false");
 return false;
 }
static bool fn2()
 {
 Console.WriteLine("fn2 is true");
 return true;
 }
public static void Main()
 {
 Console.WriteLine("regular AND:");
 bool regAnd = (fn1() & fn2());
 Console.WriteLine("result is {0}",regAnd);
 Console.WriteLine();
 Console.WriteLine("short-circuit AND:");
 bool sctAnd = (fn1() && fn2());
 Console.WriteLine("result is {0}",sctAnd);
 }
 }

Output will be

regular AND:
 fn1 is false
 fn2 is true
 result is False
short-circuit AND:
 fn1 is false
 result is False

Author : Rony T Sam

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s