Operators in C#
Operators are the symbols C# uses to perform computation, comparison, and logic on operands. They range from familiar arithmetic operators (+, -, *, /, %) shared with nearly every C-family language, to C#-specific conveniences like the null-conditional operator (?.) and the null-coalescing assignment operator (??=), which make working with nullable data significantly terser and safer. Every operator has a defined precedence and associativity that determines evaluation order in a compound expression, and most operators can be overloaded on custom types to give user-defined classes and structs natural, idiomatic syntax.
Cricket analogy: Just as a boundary counts differently depending on whether it crosses the rope on the ground or in the air, C# operators like ?. and ??= apply defined rules for evaluating nullable data safely and tersely, avoiding a clumsy manual check every time.
Arithmetic, Comparison, and Logical Operators
Arithmetic operators (+, -, *, /, %) work on numeric types, with integer division truncating toward zero (7 / 2 == 3) unless at least one operand is a floating-point type. Comparison operators (==, !=, <, >, <=, >=) return bool. Logical operators (&&, ||, !) short-circuit — && and || skip evaluating the right-hand operand when the result is already determined by the left, which matters when the right operand has side effects or could throw (e.g., a null check before a member access).
Cricket analogy: Integer division truncating 7/2 to 3 is like counting completed overs from balls bowled, dropping any partial over, while && short-circuiting is like an umpire skipping the no-ball check once a wide has already been called.
Null-Conditional and Null-Coalescing Operators
C# offers several operators purpose-built for working safely with potentially-null references: ?. (null-conditional member access) returns null instead of throwing if the left-hand side is null; ?? (null-coalescing) supplies a default when the left-hand expression is null; and ??= (null-coalescing assignment) assigns a value to a variable only if it is currently null. These operators dramatically reduce verbose null-check boilerplate that would otherwise require explicit if statements.
Cricket analogy: The ?. operator checking scorer?.CurrentOver is like a commentator safely saying 'no update yet' instead of crashing the broadcast when the scoring app hasn't connected, while ??= fills in a default team name only if none was entered.
// Arithmetic and integer division
int total = 7 / 2; // 3 (integer division truncates)
double precise = 7.0 / 2; // 3.5
// Short-circuiting logical AND avoids a NullReferenceException
string? name = null;
if (name != null && name.Length > 0)
{
Console.WriteLine("Has a name");
}
// Null-conditional and null-coalescing operators achieve the same safety more concisely
int nameLength = name?.Length ?? 0;
Console.WriteLine(nameLength); // 0, since name is null
// Null-coalescing assignment: only assigns if currently null
List<string>? cache = null;
cache ??= new List<string>();
cache.Add("first item");
// Compound assignment operators
int counter = 0;
counter += 5; // counter is now 5
counter *= 2; // counter is now 10C# allows custom operator overloading via the operator keyword, letting user-defined types like a Money or Vector2 struct support +, -, ==, and other operators naturally: public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);. This is more restrictive than C++ (you cannot invent brand-new operator symbols) but covers the common cases.
The == operator behaves differently depending on type: for value types and strings it typically compares by value, but for reference types (unless overloaded) it compares by reference identity — two distinct objects with identical field values are NOT == unless the class overrides equality. Use .Equals() overrides or record types (which generate value-based equality automatically) when value comparison is intended.
- Integer division truncates toward zero; use a floating-point operand or cast to get fractional results.
&&and||short-circuit, skipping the right operand when the left already determines the result.?.safely accesses a member only if the receiver is non-null, evaluating to null otherwise.??supplies a fallback value for a null expression;??=assigns only when the variable is currently null.- Reference-type
==compares identity by default unless the type overloads equality (or is a record). - Custom types can overload arithmetic and comparison operators via the
operatorkeyword for natural syntax.
Practice what you learned
1. What is the result of `7 / 2` when both operands are int?
2. What does the `??=` operator do?
3. Why do `&&` and `||` 'short-circuit'?
4. By default, how does `==` behave for two distinct instances of an ordinary (non-record) reference type with identical field values?
5. What does the expression `name?.Length ?? 0` evaluate to when `name` is null?
Was this page helpful?
You May Also Like
Variables and Data Types
Covers how C# declares and initializes variables, its built-in value and reference types, type inference with var, and the difference between static and dynamic typing.
Conditional Statements
Explains how C# branches program flow using if/else, the ternary conditional operator, and pattern-based conditions, with guidance on readability and pitfalls.
Nullable Reference Types
See how C# 8's nullable reference types add compile-time null-safety annotations on top of the runtime's existing nullable value type system.
Pattern Matching
Survey C#'s pattern matching features — type patterns, property patterns, relational and logical patterns, and switch expressions — for expressive, safe branching.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics