пятница, 8 июня 2012 г.

C#: Difference between && and &

(I'll write in English, because this problem is widely asked.)

What's the difference between && and & or || and | in C#? In C++ it's the difference between logical and bitwise AND.

The most of its usage as connected with universality of if in C++. For example, if(a) in C++ never executes when:
  • a is false (because false = 0)
  • a is null (because null = 0)
  • a is a number <=0.

So, if(a == true) or  (a > 0) is useless in C++. if(a) is much shorter.


JavaScript implemented 1 more option:
  • a is an empty string ("")
C# is a strongly-typed langauge and the if in C# works different. It accepts only boolean values in scope.

So, the only difference between | an || and & and && in C# is the short-circuiting.

i.e.:


if(foo() && boo())


if foo() == false, boo() willn't be executed.


if(foo() & boo())


The foo() and boo() will be executed.


So, never write this way:


if(a != 0 & b / a > 100)


if a == 0, it will fall in Division by DivideByZeroException. The right variant is:


if(a != 0 && b / a > 100)

The same thing:

 if(item != null & item.isActive())

Never write this way. It has to be written like this:


 if(item != null && item.isActive())

Комментариев нет:

Отправить комментарий