Quick Reference
operator는 operand를 계산하는 syntax이고, precedence보다 operand evaluation과 short-circuit 여부가 side effect를 결정합니다. boolean 조건에는 보통 &&/||, bit flag에는 &/|/^, overflow 확인에는 checked를 사용합니다.
int quotient = 10 / 3; // 3
bool passed = score >= 60;
bool canEnter = hasTicket && IsOpen(); // 왼쪽 false면 IsOpen 미실행
bool bothEvaluated = hasTicket & IsOpen(); // 양쪽 실행
const int Read = 1;
const int Write = 2;
int flags = Read | Write;
string label = isAdmin ? "admin" : "user";=는 대입 expression이고==는 equality test입니다. boolean 대입은if안에서도 compile될 수 있습니다.&/|는booloperand에도 쓸 수 있지만 short-circuit하지 않습니다.- integer
/는 zero 방향으로 truncation하고,%는 remainder입니다. <<,>>,>>>는 bit shift입니다. 곱셈·나눗셈 대용으로 가정하지 않습니다.
산술, 대입, 비교
int left = 10;
int right = 3;
int quotient = left / right; // 3
int remainder = left % right; // 1
left += 2;
int before = left++;
int after = ++left;integer arithmetic는 type range를 넘으면 overflow context의 영향을 받습니다. checked에서는 OverflowException이 나고, unchecked에서는 wrapping/unspecified conversion 결과를 가질 수 있습니다. validation이 목적이면 result를 보지 말고 input range를 먼저 검사합니다.
int maximum = int.MaxValue;
int wrapped = unchecked(maximum + 1);
// int failed = checked(maximum + 1); // OverflowException==의 의미는 operand type에 따라 다릅니다. numeric은 값, string은 overloaded value comparison, plain class는 기본적으로 reference identity를 비교할 수 있습니다. user-defined equality가 있을 때 null 검사에는 is null/is not null pattern이 operator overload를 호출하지 않습니다.
bool sameReference = ReferenceEquals(first, second);
bool nullValue = candidate is null;조건 평가와 bit operation
static bool Report(string name, bool value)
{
Console.WriteLine(name);
return value;
}
bool shortCircuit = Report("left", false) && Report("right", true);
bool bothSides = Report("left", false) & Report("right", true);&&, ||, ??, ?., ?:는 left operand 결과에 따라 뒤 operand를 conditionally evaluate합니다. 대부분의 다른 binary operator는 operand를 left-to-right로 evaluate합니다. precedence가 헷갈리거나 side effect가 있으면 parentheses로 의도를 고정합니다.
bitwise operation은 integral type의 bits를 다룹니다. shift count는 underlying integer width 규칙에 따라 mask되며, signed right shift >>와 zero-fill right shift >>>는 음수에서 결과가 다릅니다. protocol·flag code에는 named constant/enum과 test를 두고 magic number를 피합니다.
int read = 0b_0001;
int write = 0b_0010;
int permissions = read | write;
bool canWrite = (permissions & write) != 0;분기와 표현식 읽기
bool enabled = false;
if (enabled = ReadEnabled())
{
// boolean assignment expression은 compile됩니다.
}대입을 condition에 넣는 것이 문법 오류라고 믿으면 이 bug를 놓칠 수 있습니다. assignment와 comparison을 한 statement에 섞지 않고, 필요한 경우 별도 line으로 분리합니다.
conditional ?:는 값 하나를 선택할 때 좋습니다. 여러 branch의 validation·side effect가 커지면 if, switch, method로 분리합니다. ??와 null conditional의 범위는 null 조건·병합 연산자에서, value selection pattern은 pattern matching에서 다룹니다.
자주 틀리는 부분
&/|를 boolean expression에 썼을 때 양쪽 method가 실행됩니다. null guard, bounds guard, costly work를 오른쪽에 두는 조건은 &&/||인지 반드시 확인하세요.
++/--를 nested expression에 여러 번 넣으면 evaluation order를 사람이 추적하기 어려워집니다. increment와 사용을 별도 statement로 나누는 편이 더 안전합니다.
참고 링크
2 sources