Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

bitwise operators - A clear, layman's explanation of the difference between | and || in c#?

Ok, so I've read about this a number of times, but I'm yet to hear a clear, easy to understand (and memorable) way to learn the difference between:

if (x | y)

and

if (x || y)

..within the context of C#. Can anyone please help me learn this basic truth, and how C# specifically, treats them differently (because they seem to do the same thing). If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

|| is the logical-or operator. See here. It evaluates to true if at least one of the operands is true. You can only use it with boolean operands; it is an error to use it with integer operands.

// Example
var one = true || bar();   // result is true; bar() is never called
var two = true | bar();    // result is true; bar() is always called

| is the or operator. See here. If applied to boolean types, it evaluates to true if at least one of the operands is true. If applied to integer types, it evaluates to another number. This number has each of its bits set to 1 if at least one of the operands has a corresponding bit set.

// Example
var a = 0x10;
var b = 0x01;
var c = a | b;     // 0x11 == 17
var d = a || b;    // Compile error; can't apply || to integers
var e = 0x11 == c; // True

For boolean operands, a || b is identical to a | b, with the single exception that b is not evaluated if a is true. For this reason, || is said to be "short-circuiting".

If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?

As noted, the difference isn't irrelevant, so this question is partially moot. As for a "best practice", there isn't one: you simply use whichever operator is the correct one to use. In general, people favor || over | for boolean operands since you can be sure it won't produce unnecessary side effects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...