|| เรียกว่า Logical OR Operator และ | เรียกว่า Bitwise Logical OR แต่ความแตกต่างพื้นฐานระหว่างพวกมันอยู่ที่วิธีการ Execute Syntax สำหรับ || และ | เหมือนกันดังนี้:
bool_exp1 || bool_exp2bool_exp1 | bool_exp2- Syntax ของ 1 และ 2 ดูคล้ายกันแต่การ Execute แตกต่างกันโดยสิ้นเชิง
Logical OR (||) - Short-circuit Evaluation
- Statement แรก
bool_exp1จะถูก Execute ก่อน - ผลลัพธ์ของ Expression นี้จะตัดสินใจการ Execute Statement ถัดไป
- ถ้าเป็น
trueแล้ว OR จะเป็น true ทำให้ไม่จำเป็นต้อง Execute Statement อีกตัว bool_exp2จะ Execute ก็ต่อเมื่อbool_exp1คืนค่าfalse- เรียกว่า Short-circuit Operator เพราะมัน Short (ตัด) Circuit (Statement) บนพื้นฐานของผลลัพธ์ Expression แรก
ตัวอย่าง Logical OR (||)
using System;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
if (Condition1() || Condition2()) {
Console.WriteLine("Logical OR If Condition Executed");
}
Console.ReadLine();
}
static bool Condition1() {
Console.WriteLine("Condition 1 executed");
return true;
}
static bool Condition2() {
Console.WriteLine("Condition 2 executed");
return true;
}
}
}
Output
Condition 1 executed
Logical OR If Condition Executed
สังเกต: Condition2 ไม่ถูก Execute เพราะ Condition1 คืนค่า true แล้ว
Bitwise Logical OR (|) - Non Short-circuit
- Compiler จะ Execute ทั้งสอง Statement
- ทั้งสอง Statement ถูก Execute ไม่สนใจผลลัพธ์ของ Statement หนึ่ง
- เป็นวิธีที่ไม่มีประสิทธิภาพ (Inefficient) เพราะไม่จำเป็นต้อง Execute Statement อีกตัวถ้าตัวหนึ่งเป็น true แล้ว
- ผลลัพธ์ของ OR มีผลจริงเฉพาะเมื่อทั้งสองเป็น false
ตัวอย่าง Bitwise Logical OR (|)
using System;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
if (Condition1() | Condition2()) {
Console.WriteLine("Bitwise OR If Condition Executed");
}
Console.ReadLine();
}
static bool Condition1() {
Console.WriteLine("Condition 1 executed");
return true;
}
static bool Condition2() {
Console.WriteLine("Condition 2 executed");
return true;
}
}
}
Output
Condition 1 executed
Condition 2 executed
Bitwise OR If Condition Executed
สังเกต: Condition1 และ Condition2 ถูก Execute ทั้งคู่
การใช้งาน | กับ Integer (Bitwise Operation)
นอกจาก Boolean แล้ว | ยังใช้กับ Integer สำหรับ Bitwise Operation:
int a = 5; // 0101
int b = 3; // 0011
int result = a | b; // 0111 = 7
Console.WriteLine(result); // 7
สรุป
| Operator | ชื่อ | Short-circuit | ใช้กับ |
|---|---|---|---|
|| | Logical OR | Yes | Boolean |
| | Bitwise/Logical OR | No | Boolean, Integer |
&& | Logical AND | Yes | Boolean |
& | Bitwise/Logical AND | No | Boolean, Integer |
Best Practice: ใช้ || และ && สำหรับ Boolean Logic (Performance ดีกว่าและป้องกัน NullReferenceException ได้) ใช้ | และ & สำหรับ Bitwise Operations หรือเมื่อต้องการ Evaluate ทั้งสองฝั่งเสมอ