3. Operators
Operators perform work on values. Arithmetic: + - * / % (remainder). Comparison: == != < > <= >= (they produce bool). Logical: && (and), || (or), ! (not); && and || short-circuit, so the right side is only evaluated when needed. Assignment: = and the compound forms += -= *= /= %=. Increment ++ and decrement -- add or subtract one, and their position matters: i++ returns the old value, ++i returns the new one.
Dividing two ints gives an int result, so 7 / 2 is 3 (use a double on one side for 3.5), and integer division by zero throws an exception while double division by zero gives Infinity. Bitwise operators work on the bits of integers: & (and), | (or), ^ (xor), ~ (not), << and >> (shift). The ?: operator is a short if/else, ?? supplies a default when a value is null, ??= assigns only when the variable is null, and ?. stops safely when an object is null.
Other useful operators: is (type or pattern test), as (safe cast), typeof, nameof, and the index-from-end (^) and range (..) operators used with arrays and strings. The Math class provides Round, Floor, Ceiling, Pow, Sqrt, Abs, Min, Max and more. When operators are mixed, precedence decides the order (* and / before + and -); use parentheses to be explicit.
Key points to remember
- Precedence from high to low: unary (! ++ --), * / %, + -, comparisons, == !=, &&, ||, ?? , ?:, assignment.
- Use == to compare and = to assign. if (x = 5) is a compile error in C#, which protects you from the classic mistake.
- For strings, == compares the text; for most other reference types it compares whether they are the same object, unless == is overloaded (as it is for string and records).
- Math.Round uses banker's rounding by default (2.5 becomes 2). Pass MidpointRounding.AwayFromZero for the school-book rule.
- Bit shifting left by n multiplies by 2^n and shifting right divides by 2^n for non-negative integers.
- Floating-point numbers are approximate: never compare doubles with == after calculations; compare the difference to a tiny tolerance, or use decimal.
- Use checked(...) when overflow must be detected rather than silently wrapping.
Example 1: Arithmetic and comparison
int x = 7, y = 2; Console.WriteLine(x / y); // integer division Console.WriteLine(x % y); // remainder Console.WriteLine((double)x / y); Console.WriteLine(x > y && y > 0); Console.WriteLine(5.0 / 0); // double division by zero
Show output
Output3 1 3.5 True Infinity
Example 2: Increment, decrement and compound assignment
int i = 5; Console.WriteLine(i++); // uses 5, then adds 1 Console.WriteLine(i); Console.WriteLine(++i); // adds 1, then uses 7 int total = 10; total += 5; // 15 total *= 2; // 30 total -= 4; // 26 total /= 2; // 13 total %= 7; // 6 Console.WriteLine(total);
Show output
Output5 6 7 6
Example 3: Logical operators and short-circuiting
int x = 0; bool safe = x != 0 && 10 / x > 1; // right side never runs, so no error Console.WriteLine(safe); bool a = true, b = false; Console.WriteLine(a & b); // and Console.WriteLine(a | b); // or Console.WriteLine(a ^ b); // exclusive or Console.WriteLine(!a); // not
Show output
OutputFalse False True True False
Example 4: Bitwise and shift operators
int p = 6; // binary 110 int q = 3; // binary 011 Console.WriteLine(p & q); // 010 Console.WriteLine(p | q); // 111 Console.WriteLine(p ^ q); // 101 Console.WriteLine(~p); // flips every bit Console.WriteLine(p << 1); // 6 * 2 Console.WriteLine(p >> 1); // 6 / 2
Show output
Output2 7 5 -7 12 3
Example 5: Ternary and null operators
int age = 20; string status = age >= 18 ? "Adult" : "Minor"; string input = null; string name = input ?? "Guest"; // default when null input ??= "Default"; // assign only when null Console.WriteLine(status); Console.WriteLine(name); Console.WriteLine(input); Console.WriteLine(input?.Length); // 7, or null if input were null
Show output
OutputAdult Guest Default 7
Example 6: The Math class
Console.WriteLine(Math.Round(3.14159, 2)); Console.WriteLine(Math.Round(2.5)); // banker's rounding Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero)); Console.WriteLine(Math.Floor(7.9)); Console.WriteLine(Math.Ceiling(7.1)); Console.WriteLine(Math.Pow(2, 10)); Console.WriteLine(Math.Sqrt(144)); Console.WriteLine(Math.Abs(-8)); Console.WriteLine(Math.Max(3, 9) + " " + Math.Min(3, 9));
Show output
Output3.14 2 3 7 8 1024 12 8 9 3
Example 7: Operator precedence
Console.WriteLine(2 + 3 * 4); // multiplication first
Console.WriteLine((2 + 3) * 4); // parentheses first
Console.WriteLine(10 - 4 - 3); // left to right
Console.WriteLine(!true || true); // ! first, then ||
Console.WriteLine(1 + 2 + "3"); // numbers added, then joined as text
Console.WriteLine("1" + 2 + 3); // text joining from the start
Show output
Output14 20 3 True 33 123
Example 8: is, typeof and nameof
object o = "hello"; Console.WriteLine(o is string); Console.WriteLine(o is int); Console.WriteLine(typeof(int)); Console.WriteLine(nameof(o)); string? s = o as string; // null if the cast is not possible Console.WriteLine(s?.ToUpper());
Show output
OutputTrue False System.Int32 o HELLO