48

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody please explain with an example?

mybrave
  • 1,662
  • 3
  • 20
  • 37
BreakHead
  • 10,480
  • 36
  • 112
  • 165

9 Answers9

54

& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:

 bool f() {
    Console.WriteLine("f called");
    return false;
 }
 bool g() {
    Console.WriteLine("g called");
    return false;
 }
 static void Main() {
    bool result = f() && g(); // prints "f called"
    Console.WriteLine("------");
    result = f() & g(); // prints "f called" and "g called"
 }

|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.

Of course, user defined types can overload these operators making them do anything they want.

Vasfed
  • 18,013
  • 10
  • 47
  • 53
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • Thanx Mehrad Do you mean '&' operand is equal to '||'...?? – BreakHead Nov 12 '10 at 10:18
  • 1
    When used with boolean types `&` is a logical AND, `&&` is described as "the conditional-AND operator" (by Microsoft anyway). http://msdn.microsoft.com/en-us/library/2a723cdk.aspx – GrahamS Nov 12 '10 at 10:20
  • 1
    @BreakHead: Nope. `&&`, `&` are AND. `||`, `|` are OR. `&&` and `||` both short circuit, whereas `|` and `&` both don't short circuit. – Mehrdad Afshari Nov 12 '10 at 21:18
10

Strongly recommend this article from Dotnet Mob : http://codaffection.com/csharp-article/short-circuit-evaluation-in-c/

-&& is short-circuit logical operator

For AND operations if any of the operand evaluated to false then total expression evaluated to false, so there is no need to evaluate remaining expressions, similarly in OR operation if any of the operand evaluated to true then remaining evaluation can be skipped

-& operator can be used as either unary or binary operator. that is, unary & can be used to get address of it’s operand in unsafe context.

mybrave
  • 1,662
  • 3
  • 20
  • 37
Shamseer K
  • 4,964
  • 2
  • 25
  • 43
  • Thanks Your article is good one :) , but I guess there is a typo in this sentence `And in case of OR operation if any of the operand evaluated to true then remaining evaluations can be skipped.` In Logical | operator both operand's are evaluated not skipped. Check my [answer](https://stackoverflow.com/a/49528529/2218697). Some points I learned from yours. – Shaiju T Mar 28 '18 at 07:31
  • 1
    @stom It is a general statement - If any of the operand results in True then whole statement will be true. That is what happens with || operations (it evaluate operands from left to right). In case of | operator, nothing is skipped. Both of these | and || are OR operator. – Shamseer K Mar 28 '18 at 10:08
  • Yes you are correct for `| (pipeline) operator` all operands are evaluated but in `||(double pipeline) operator` , because of short circuiting the operands are skipped. But there is little confusion in your article because you say that sentence just after explaining logical `AND` and `OR` operators. :) – Shaiju T Mar 28 '18 at 10:18
8

& can be used on either integral types (like int, long etc.) or on bool.

When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.

&& is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.

Example where this matters:

void Action() 
{
    string name = null;
    if(name != null && name.EndsWith("ack"))
    {
        SomeOtherAction();
    }
}

If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.

If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.

One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.

Burak
  • 667
  • 1
  • 11
  • 19
5

Below example and explanation's may help.

Example:

    public static bool Condition1()
    {
        Console.WriteLine("Condition1 is evaluated.");
        return false;
    }

    public static bool Condition2()
    {
        Console.WriteLine("Condition2 is evaluated.");
        return true;
    }

1. Logical Operator

& (ampersand) Logical AND operator

| (pipeline) Logical OR operator

Used for ensuring all operands are evaluated.

if(Condition1() & Condition2())
{
  Console.WriteLine("This will not print");

  //because if any one operand evaluated to false ,  
  //thus total expression evaluated to false , but both are operand are evaluated.
}

 if (Condition2() | Condition1())
 {
   Console.WriteLine("This will print");

   //because any one operand evaluated to true ,  
  //thus total expression evaluated to true , but both are operand are evaluated.
 }

2. Conditional Short Circuit Operator

&& (double ampersand) Conditional AND operator

|| (double pipeline) Conditional OR operator

Used for Skipping the right side operands , Has Side effects so use carefully

if (Condition1() && Condition2())
{
   Console.WriteLine("This will not print");

   //because if any one operand evaluated to false,
   //thus total expression evaluated to false , 
   //and here the side effect is that second operand is skipped 
   //because first operand evaluates to false.
}

if (Condition2() || Condition1())
{
   Console.WriteLine("This will print");

  //because any one operand evaluated to true 
  //thus remaining operand evaluations can be skipped.
}

Note:

To get better understanding test it in console sample.

References

dotnetmob.com

wikipedia.org

stackoverflow.com

Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • 1
    WriteLine in Condition methods can be helpful to get a better understanding. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#logical-and-operator- – NullPointerWizard Aug 26 '21 at 13:22
3

& is a bitwise operator and && is a logical operator that applies to bool operands.

Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65
  • 6
    & is also a logical operator when the operands are bool. See http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx – GrahamS Nov 12 '10 at 10:23
2

Easy way to look it is logical & will evaluate both sides of the & regardless if the left side is false, whereas the short-circuit && will only evaluate the right side if the left is true.

d=0;
n=10;

// this throws divide by 0 exception because it evaluates the 
//      mod even though "d != 0" is false
if ( (d != 0) & (n % d) == 0 ) 
   Console.Writeline( d + " is a factor of " + n);

// This will not evaluate the mod.
if ( (d != 0) && (n % d) == 0 ) 
   Console.Writeline( d + " is a factor of " + n);
Tom
  • 162
  • 8
1

According to - C# 4.0 The Complete Reference by Herbert Schildt

& - Logical AND Operator
| - Logical OR Operator

&& - Short Circuited AND Operator
|| - Short Circuited OR Operator

A simple example can help understand the phenomena

using System;

class SCops {
    static void Main() {
        int n, d;
        n = 10;
        d = 2;

        if(d != 0 && (n % d) == 0)
            Console.WriteLine(d + " is a factor of " + n);
        d = 0; // now, set d to zero

        // Since d is zero, the second operand is not evaluated.
        if(d != 0 && (n % d) == 0)
            Console.WriteLine(d + " is a factor of " + n);
        // Now, try the same thing without the short-circuit operator.
        // This will cause a divide-by-zero error.
        if(d != 0 & (n % d) == 0)
            Console.WriteLine(d + " is a factor of " + n);
    }
}

Here the & operator checks each and every operand and && checks only the first operand.

As you might notice for 'AND' operations any operand which is false will evaluate the whole expression to false irrespective of any other operands value in the expression. This short circuited form helps evaluate the first part and is smart enough to know if the second part will be necessary.

Running the program will throw a divide-by-zero error for the last if condition where both the operands are checked for & operator and no exception handling is done to tackle the fact that 'd' can be 0 at any point of time.

The same case applies to '|' in C#.

This is slightly different than C or C++ where '&' and '|' were bitwise AND and OR operators. However C# also applies the bitwise nature of & and | for int variables only.

Joy Ram Sen Gupta
  • 365
  • 1
  • 6
  • 16
1

The first one is bitwise and the second one is boolean and.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • & is a logical (boolean) and when applied to booleans, is is however not short circuiting as && – Rune FS Jun 13 '12 at 06:46
0

Hai Friend, The Operator &&(Logical Operator) is used in conditional statements. For Instance

if(firstName == 'Tilsan' && lastName == 'Fighter')
{
      Response.Write("Welcome Tilsan The Fighter!");
}

the Response.Write statement will run only if both variables firstName and lastName match to their condition.

Whereas & (Bitwise Operator)operator is used for Binary AND operations, i.e., if we write:

bool a, b, c;

a = true;
b = false;

c = a & b;

Response.Write(c); // 'False' will be written to the web page

Here first Binary And operation will be performed on variables a and b, and the resultant value will be stored in variable c.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Sankar Ganesh PMP
  • 11,927
  • 11
  • 57
  • 90