C# Operators Complete Guide (Bitwise, Nullable, is/as & Precedence) Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 7 of 35 ๐Ÿ“‚ Phase 3: Operators & User Input ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Arithmetic ยท Assignment ยท Logical & Comparison ยท Ternary (?:) ยท Null-Coalescing (??) ยท Null-Conditional (?.) ยท is & as Operators ยท Bitwise ยท Operator Precedence

Welcome to Phase 3 (Chapter 7): C# Operators, Bitwise, Nullable & Precedence Masterclass! Operators are fundamental tokens that instruct the compiler to perform specific mathematical, logical, relational, bitwise, or type operations. In this comprehensive textbook guide, we explore all C# operators: arithmetic, assignment, compound assignment, comparison, logical, increment/decrement, unary, ternary (?:), null-coalescing (??), null-conditional (?.), bitwise operators, type-testing operators (is & as), and operator precedence rules.

1Arithmetic, Assignment & Compound Assignment Operators

Arithmetic operators perform basic mathematical calculations. Compound assignment operators combine arithmetic with assignment to write shorter, cleaner expressions.

OperatorCategoryDescriptionExample
+ArithmeticAddition (or String concatenation)5 + 3 == 8
-ArithmeticSubtraction10 - 4 == 6
*ArithmeticMultiplication4 * 5 == 20
/ArithmeticDivision (integer division truncates decimal!)7 / 2 == 3 (int) | 7.0 / 2 == 3.5
%ArithmeticModulus (remainder of division)17 % 5 == 2
+=CompoundAdd and Assignx += 5 (same as x = x + 5)
-=CompoundSubtract and Assignx -= 3
*=CompoundMultiply and Assignx *= 2
/=CompoundDivide and Assignx /= 4
%=CompoundModulus and Assignx %= 3
C# โ€” Arithmetic & Compound Assignment Code โ–ถ Run in Compiler
int price = 100;
int discount = 20;
int finalPrice = price - discount;

Console.WriteLine($"Price: {price}, Discount: {discount}, Final Price: {finalPrice}");

// Compound assignment
int score = 50;
score += 10; // 60
score *= 2;  // 120
score %= 7;  // 1
Console.WriteLine($"Calculated Score: {score}");

// Pre-increment vs Post-increment
int count = 5;
Console.WriteLine($"Pre-increment (++count): {++count}");   // Outputs 6 (increments first)
Console.WriteLine($"Post-increment (count++): {count++}");  // Outputs 6 (prints, then increments to 7)
Console.WriteLine($"Final count value: {count}");            // Outputs 7
๐Ÿ” Code Mechanics Breakdown:
  • price - discount: Subtracts integer 20 from 100, storing 80 in finalPrice.
  • ++count (Pre-increment): Modifies the variable before evaluating the surrounding expression.
  • count++ (Post-increment): Evaluates the surrounding expression using the original value before incrementing memory.
2Comparison & Logical Operators

Comparison operators compare two values and return a boolean (true or false). Logical operators combine multiple boolean expressions.

C# โ€” Comparison & Logical Operators โ–ถ Run in Compiler
int age = 20;
bool hasID = true;

// Comparison: ==, !=, >, <, >=, <=
// Logical AND (&&): true ONLY IF both conditions are true
bool canEnterClub = (age >= 18) && hasID;
Console.WriteLine($"Can enter club: {canEnterClub}");

// Logical OR (||): true IF AT LEAST ONE condition is true
bool isWeekend = true;
bool isHoliday = false;
bool canRest = isWeekend || isHoliday;
Console.WriteLine($"Can rest: {canRest}");

// Logical NOT (!): Inverts boolean value
bool isRaining = false;
Console.WriteLine($"Is clear weather: {!isRaining}");

// Ternary Operator (condition ? valueIfTrue : valueIfFalse)
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine($"User Status: {status}");
3Null Operators โ€” Null-Conditional (?.) & Null-Coalescing (??)

C# provides built-in operators specifically designed to handle null values safely without throwing dangerous NullReferenceException crashes:

C# โ€” Null Handling Operators โ–ถ Run in Compiler
string? name = null;

// 1. Null-Conditional Operator (?.) โ€” Safe property access
// If name is null, returns null instead of throwing NullReferenceException!
int? nameLength = name?.Length;
Console.WriteLine($"Length: {nameLength?.ToString() ?? "null"}");

// 2. Null-Coalescing Operator (??) โ€” Fallback value if null
string displayName = name ?? "Guest User";
Console.WriteLine($"Hello, {displayName}!");

// 3. Null-Coalescing Assignment Operator (??=) โ€” Assigns value ONLY IF variable is null
name ??= "Default Ravi";
Console.WriteLine($"Name after ??=: {name}");
4Type Testing & Casting โ€” is and as Operators

When working with object hierarchies or interface references, the is and as operators provide safe type checking and casting:

C# โ€” is and as Operators โ–ถ Run in Compiler
object data = "Hello C# Masterclass";

// 1. 'is' operator with pattern matching variable declaration
if (data is string text)
{
    Console.WriteLine($"data is a string of length {text.Length}: '{text}'");
}

// 2. 'as' operator (safe cast โ€” returns null if conversion fails, NO EXCEPTION!)
string? strVal = data as string;
if (strVal != null)
{
    Console.WriteLine($"Safe cast string upper: {strVal.ToUpper()}");
}

object numObj = 42;
string? badCast = numObj as string; // badCast is null (does not throw exception!)
Console.WriteLine($"Bad cast result: {badCast ?? "NULL"}");
5Bitwise Operators

Bitwise operators manipulate data at the individual binary bit level (0 and 1). They are heavily used in graphics programming, low-level networking, cryptography, and flags.

OperatorNameOperationExample (a=5 / 0101, b=3 / 0011)
&Bitwise AND1 if both bits are 15 & 3 == 1 (0001)
|Bitwise OR1 if at least one bit is 15 | 3 == 7 (0111)
^Bitwise XOR1 if bits are different5 ^ 3 == 6 (0110)
~Bitwise NOTInverts all bits~5 == -6
<<Left ShiftShifts bits left (multiplies by 2^n)5 << 1 == 10
>>Right ShiftShifts bits right (divides by 2^n)5 >> 1 == 2
6Operator Precedence Table

When an expression contains multiple operators, operator precedence determines the order of evaluation (from highest to lowest):

Precedence RankCategoryOperators
1 (Highest)Primary / Postfixx.y, x?.y, f(x), a[i], x++, x--, new
2Unary+x, -x, !x, ~x, ++x, --x, (Type)x, await
3Multiplicative*, /, %
4Additive+, -
5Shift<<, >>
6Relational & Type<, >, <=, >=, is, as
7Equality==, !=
8Logical AND&
9Logical XOR^
10Logical OR|
11Conditional AND&&
12Conditional OR||
13Null-Coalescing??
14Ternaryc ? t : f
15 (Lowest)Assignment=, +=, -=, *=, /=, %=, ??=
7Technical FAQs

Q1: What is short-circuit evaluation in && and || operators?

Short-circuit evaluation means the compiler stops evaluating an expression as soon as the result is determined. For &&, if the first condition is false, the second condition is completely skipped. For ||, if the first condition is true, the second condition is skipped.

Q2: How does the 'as' operator differ from explicit casting (Type)obj?

Explicit casting (string)obj throws an InvalidCastException if the object is not of that type. The as operator performs a safe cast and returns null if the cast fails without throwing any exception.

Q3: What is the difference between ?? and ??= ?

a ?? b returns b if a is null. a ??= b assigns b to a ONLY IF a is currently null.