Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between & and && operators in C#

Tags:

c#

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?

like image 340
BreakHead Avatar asked Nov 12 '10 10:11

BreakHead


2 Answers

& 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.

like image 174
mmx Avatar answered Sep 26 '22 08:09

mmx


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.

like image 28
Shamseer K Avatar answered Sep 23 '22 08:09

Shamseer K