Operators are basic tools for manipulating values. In addition to the common Arithmetic/Comparison/Logic, C# is rich in expression-friendly features such as the null safe operator, pattern matching (is), and ternary operator (?:).
Learning Objectives
- Know the priority of the Arithmetic/Comparison/Logic operator.
- Understand the difference in results between
int / intanddouble / int - Know the short-circuit operation of
&&/|| - Handle null safely with
?.????= - Type check and conversion with
is/as - Write expressions concisely with the ternary operator
?:
Key concepts
1) Arithmetic operators
There are +, -, *, /, and %. The key is type rules.
int x = 7 / 2; //3 (integer division, decimal point truncated)
double y = 7 / 2; //3.0 (first integer division and then double conversion)
double z = 7.0 / 2; //3.5 (if one side is double, real number division)
int r = 7 % 2; //1 (remainder)
2) Comparison and logical operators
- Comparison:
==,!=,<,<=,>,>=→boolreturns - Logic:
&&(AND),||(OR),!(NOT)
Short-circuit evaluation: && does not look to the right if false is to the left. || does not look to the right if true is to the left.
int? n = null;
if (n != null && n.Value > 0) //If n == null, .Value is not evaluated.
Console.WriteLine("positive number");
3) Null-conditional ?. and null-coalescing ??, ??=
obj?.Member: Ifobjisnull, the entire evaluation isnull, otherwise,Memberis evaluated.a ?? b: Ifaisnull, thenba ??= b: Substitutebonly whenaisnull
string? name = null;
int len = name?.Length ?? 0; //If null it is 0
name ??= "(no name)"; //Assign only when null
Console.WriteLine($"{name} ({len})"); //(no name) (0)
4) is and as
obj is Type: If the type istrue, it can be combined with pattern matching.obj as Type: When casting fails,null** instead of **exception
object o = "hello";
if (o is string s) //Type checking + variable declaration
Console.WriteLine(s.Length); // 5
object o2 = 42;
string? s2 = o2 as string; //Casting failed → s2 == null
5) Ternary operator ?:
"condition ? true value : false value" — short if-else as an expression.
int score = 75;
string grade = score >= 60 ? "passed" : "failed";
See as example
Example 1 — Arithmetic/Program.cs: Integer vs real division
int a = 7, b = 2;
Console.WriteLine($"{a} + {b} = {a + b}");
Console.WriteLine($"{a} - {b} = {a - b}");
Console.WriteLine($"{a} * {b} = {a * b}");
Console.WriteLine($"{a} / {b} = {a / b} (integer division)");
Console.WriteLine($"{a} % {b} = {a % b}");
Console.WriteLine($"(double)a / b = {(double)a / b} (real division)");
Execution result
7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3 (integer division)
7 % 2 = 1
(double)a / b = 3.5 (real division)
Note: Even if you cast only one side as (double), the result will be double.
Example 2 — LogicalOps/Program.cs: Demonstrating short-circuit evaluation
static bool Log(string label, bool value)
{
Console.WriteLine($"[{label} evaluated → {value}]");
return value;
}
Console.WriteLine("(false &&");
bool r1 = Log("A", false) && Log("B", true);
Console.WriteLine($" => {r1}");
Console.WriteLine("(true ||");
bool r2 = Log("C", true) || Log("D", false);
Console.WriteLine($" => {r2}");
Execution result
(false &&
[A rated → False]
=> False
(true ||
[Rated C → True]
=> True
Note: B, D are not evaluated. This is a paragraph evaluation.
Example 3 — NullSafety/Program.cs : ?. ?? ??=
string? name = null;
int len = name?.Length ?? 0; //If null it is 0
Console.WriteLine($"Length: {len}");
name ??= "(no name)"; //Assign only when null
Console.WriteLine($"Name: {name}");
//Once again: now it's not null so it doesn't change
name ??= "another default";
Console.WriteLine($"final: {name}");
Execution result
Length: 0
Name: (no name)
Final: (unnamed)
Memo: When ?. is null, the entire expression becomes null. So I often use it as a companion to ??.
Example 4 — IsAs/Program.cs: Type checking and casting
object[] items = ["hello", 42, 3.14, true];
foreach (object item in items)
{
if (item is string s)
Console.WriteLine($"String: '{s}' (length {s.Length})");
else if (item is int n)
Console.WriteLine($"integer: {n}");
else
Console.WriteLine($"Other: {item} ({item.GetType().Name})");
}
object boxed = 100;
string? wrong = boxed as string; //Casting failed → null
Console.WriteLine($"as result: {wrong ??"(null)"}");
Execution result
String: 'hello' (length 5)
Integer: 42
Others: 3.14 (Double)
Other: True (Boolean)
as result: (null)
Note: The is Type variable pattern is the cleanest. If you force cast like (string)boxed, an exception will occur if it fails, so if you want to be safe, use as or is.
Common Mistakes
- Expect
7 / 2to be3.5— Integer division between integers. - Confusion between
=and==likeif (count = 0)— In C#, an expression other thanboolcannot be inserted intoif, so a compilation error occurs, so it is safe, but be careful. - Confusion between
??and?:—??is null or not, and?:is general condition. - Cast value type as
as—as intis not possible, must be written asas int?. - Access the object
nullas.→NullReferenceException. Always consider?..
Cleanup
- Integer Division/Real-numbers distinguishes division
- Safe null check and chain check with short circuit evaluation of
&&/|| ?.????=is a set of 3 null processing- Safely check and convert types with
is/as - Ternary
?:neatly expresses short branches
Try it yourself
cd src/Arithmetic && dotnet run
cd ../LogicalOps && dotnet run
cd ../NullSafety && dotnet run
cd ../IsAs && dotnet run