Operators and Expressions
Arithmetic Operators
Arithmetic operators perform basic math operations including addition, subtraction, multiplication, division, and modulus.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 7 / 2 |
3 |
% |
Modulus | 7 % 2 |
1 |
Warning: Integer division truncates the decimal part.
7 / 2yields3, not3.5. To get a floating-point result, at least one operand must be a floating-point type, e.g.,7.0 / 2yields3.5.
Example
using System;
class Program
{
static void Main()
{
int a = 17, b = 5;
Console.WriteLine($"Addition: {a} + {b} = {a + b}");
Console.WriteLine($"Subtraction: {a} - {b} = {a - b}");
Console.WriteLine($"Multiplication: {a} * {b} = {a * b}");
Console.WriteLine($"Integer division: {a} / {b} = {a / b}");
Console.WriteLine($"Floating-point division: {a * 1.0} / {b} = {a * 1.0 / b}");
Console.WriteLine($"Modulus: {a} % {b} = {a % b}");
}
}
Addition: 17 + 5 = 22
Subtraction: 17 - 5 = 12
Multiplication: 17 * 5 = 85
Integer division: 17 / 5 = 3
Floating-point division: 17 / 5 = 3.4
Modulus: 17 % 5 = 2
Increment and Decrement Operators
The increment ++ and decrement -- operators increase or decrease a variable's value by 1. The prefix form modifies the value before use; the postfix form uses the value first, then modifies it.
| Operator | Name | Description |
|---|---|---|
++x |
Prefix increment | Increment by 1, then use the value |
x++ |
Postfix increment | Use the value, then increment by 1 |
--x |
Prefix decrement | Decrement by 1, then use the value |
x-- |
Postfix decrement | Use the value, then decrement by 1 |
Example
using System;
class Program
{
static void Main()
{
int x = 10;
int y = 10;
Console.WriteLine($"Prefix increment: ++x = {++x}, x = {x}");
Console.WriteLine($"Postfix increment: y++ = {y++}, y = {y}");
int m = 5;
int n = 5;
Console.WriteLine($"Prefix decrement: --m = {--m}, m = {m}");
Console.WriteLine($"Postfix decrement: n-- = {n--}, n = {n}");
}
}
Prefix increment: ++x = 11, x = 11
Postfix increment: y++ = 10, y = 11
Prefix decrement: --m = 4, m = 4
Postfix decrement: n-- = 5, n = 4
Relational Operators
Relational operators compare two values and return a bool result (true or false).
| Operator | Name | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
true |
!= |
Not equal to | 5 != 3 |
true |
< |
Less than | 3 < 5 |
true |
> |
Greater than | 5 > 3 |
true |
<= |
Less than or equal | 5 <= 5 |
true |
>= |
Greater than or equal | 5 >= 6 |
false |
Tip: Do not confuse
=(assignment) with==(equality check). Using=in anifcondition causes a compile error or logic bug.
Logical Operators
Logical operators combine boolean expressions. C# uses && and || with short-circuit evaluation, meaning the second operand is not evaluated when the result is already determined.
| Operator | Name | Example | Description |
|---|---|---|---|
&& |
Logical AND | a && b |
True if both are true (short-circuit) |
| ` | ` | Logical OR | |
! |
Logical NOT | !a |
Negates the value |
Warning: Use
&&and||for logical operations in C#, not&and|. The latter are bitwise operators that can also operate on booleans but do not short-circuit.
Example
using System;
class Program
{
static void Main()
{
int age = 25;
bool hasLicense = true;
bool canDrive = age >= 18 && hasLicense;
Console.WriteLine($"Can drive: {canDrive}");
bool isWeekend = false;
bool isHoliday = true;
bool dayOff = isWeekend || isHoliday;
Console.WriteLine($"Day off: {dayOff}");
bool isRaining = true;
Console.WriteLine($"Not raining: {!isRaining}");
}
}
Can drive: True
Day off: True
Not raining: False
Assignment Operators
Assignment operators assign values to variables. Compound assignment operators combine an operation and assignment into one step.
| Operator | Equivalent | Example |
|---|---|---|
= |
x = 10 |
|
+= |
x = x + y |
x += 5 |
-= |
x = x - y |
x -= 3 |
*= |
x = x * y |
x *= 2 |
/= |
x = x / y |
x /= 4 |
%= |
x = x % y |
x %= 3 |
Conditional Operator
The conditional operator ?: is C#'s only ternary operator. It returns one of two values based on a condition.
Syntax: condition ? valueIfTrue : valueIfFalse
Example
using System;
class Program
{
static void Main()
{
int score = 72;
string result = score >= 60 ? "Pass" : "Fail";
Console.WriteLine($"Score {score}: {result}");
int a = 15, b = 9;
int max = a > b ? a : b;
Console.WriteLine($"Larger value: {max}");
}
}
Score 72: Pass
Larger value: 15
Null-Coalescing Operator
The ?? operator returns the right-hand operand when the left-hand operand is null; otherwise, it returns the left-hand value. The ??= operator (C# 8) is the null-coalescing assignment operator that assigns a value only when the variable is null.
using System;
class Program
{
static void Main()
{
string name = null;
string display = name ?? "Anonymous";
Console.WriteLine($"Name: {display}");
int? count = null;
int total = count ?? 0;
Console.WriteLine($"Total: {total}");
string title = null;
title ??= "Default Title";
Console.WriteLine($"Title: {title}");
title ??= "New Title";
Console.WriteLine($"Title: {title}");
}
}
Name: Anonymous
Total: 0
Title: Default Title
Title: Default Title
Null-Conditional Operator
The ?. operator checks whether an object is null before accessing a member. If the object is null, the expression returns null instead of throwing a NullReferenceException.
using System;
class Program
{
static void Main()
{
string text = "Hello C#";
Console.WriteLine($"Length: {text?.Length}");
text = null;
Console.WriteLine($"Length: {text?.Length}");
int? len = text?.Length;
Console.WriteLine($"Type: {len?.GetType().Name ?? "null"}");
}
}
Length: 8
Length:
Type: null
Operator Precedence
The table below lists common C# operators from highest to lowest precedence. Operators on the same row have equal precedence.
| Priority | Operators | Description |
|---|---|---|
| 1 | x++ x-- . ?. () [] |
Postfix, member access |
| 2 | ++x --x +x -x ! ~ |
Prefix, unary |
| 3 | * / % |
Multiplicative |
| 4 | + - |
Additive |
| 5 | < > <= >= is as |
Relational, type check |
| 6 | == != |
Equality |
| 7 | && |
Logical AND |
| 8 | ` | |
| 9 | ?? ??= |
Null-coalescing |
| 10 | ?: |
Conditional |
| 11 | = += -= *= /= %= etc. |
Assignment |
Tip: When in doubt about precedence, use parentheses
()to make the evaluation order explicit. This prevents errors and improves readability.
❓ FAQ
7 / 2 yields 3; floating-point division preserves decimals, e.g., 7.0 / 2 yields 3.5.++x and x++?++x increments first and returns the new value; x++ returns the current value then increments. In a standalone statement they behave the same, but within an expression the results differ.&& and &?&& is a short-circuit logical AND that skips the right operand when the left is false; & is a bitwise AND that can also operate on booleans but always evaluates both sides.?? vs ?.??? to provide a default value when null; use ?. to safely access a member on a potentially null object, avoiding NullReferenceException.📖 Summary
- Arithmetic operators perform math calculations; note that integer division truncates decimals
- Increment and decrement have prefix and postfix forms that differ in evaluation timing
- Relational operators return
boolvalues for conditional logic - Logical operators
&&and||support short-circuit evaluation - Compound assignment operators combine an operation with assignment
- The conditional operator
?:is a concise ternary selection expression ??provides a default for null,?.safely accesses members, and??=assigns only when null- Precedence from high to low: postfix -> unary -> multiplicative -> additive -> relational -> equality -> logical AND -> logical OR -> null-coalescing -> conditional -> assignment
📝 Exercises
- Write a program that computes
7 / 2and7.0 / 2and outputs the results, verifying the truncation behavior of integer division. - Write a program demonstrating the difference between
++xandx++in an expression: setint a = 5, then compute++a * 3anda++ * 3separately and output the results. - Write a program that uses the conditional operator to determine whether an integer is positive, zero, or negative (nesting
?:is allowed). - Write a program that creates a
stringvariable set tonull, then uses??and?.to output its default value and safely access its length. - Write a program that evaluates
2 + 3 * 4and(2 + 3) * 4, demonstrating how parentheses affect precedence.



