Lesson 5 of 24
In progress
Operators and null handling
Arithmetic, comparison and logical operators, plus the null-conditional and null-coalescing forms that keep C# readable.
C# has the operators you expect from a C-family language, plus two that exist because null is part of everyday code: ?. and ??.
What you will learn
- Use arithmetic, comparison and logical operators correctly.
- Chain null-conditional access safely.
- Prefer pattern checks to casts when testing types.
Arithmetic
int a = 7, b = 2;
Console.WriteLine(a / b); // 3
Console.WriteLine(a % b); // 1
Console.WriteLine(a / 2.0); // 3.5
decimal price = 100m;
Console.WriteLine(price * 1.18m); // 118.00
Integer division truncates toward zero. % returns a remainder with the sign of the dividend, so -7 % 2 is -1, which matters when you compute an index.
Mixing int and decimal promotes to decimal; mixing int and double promotes to double. A decimal and a double cannot be combined without an explicit cast, precisely because the conversion loses precision.
Compound assignment and increment
int total = 10;
total += 5; // 15
total *= 2; // 30
total++; // 31
i++ returns the old value and then increments; ++i increments first. In a statement by itself they are identical, so keep them that way.
Comparison and logical operators
bool member = true;
bool coupon = false;
decimal total = 1200m;
bool discount = (member || coupon) && total >= 1000m;
&& and || short-circuit, so a null check can guard the expression after it. & and | evaluate both operands and are for bitwise work.
! negates. Parenthesise mixed expressions: && binds tighter than ||, and the intent is worth making visible.
Null-conditional access
string? name = null;
Console.WriteLine(name?.Length); // null, no exception
Console.WriteLine(name?.ToUpper()); // null
?. evaluates to null when the left side is null, instead of throwing. It works for method calls, indexers (list?[0]) and chained access.
Chaining is the useful part:
string? city = order?.Customer?.Address?.City;
Each link is checked, so a missing customer produces null rather than a NullReferenceException. The type becomes nullable, which forces the caller to decide what a missing city means.
Null-coalescing
string display = name ?? "anonymous";
int length = name?.Length ?? 0;
?? returns the left operand unless it is null. Combined with ?., it supplies a default at the end of a chain.
??= assigns only when the target is null:
List<string>? tags = null;
tags ??= new List<string>();
tags.Add("new");
That pattern is the C# equivalent of "create if missing" and reads well at the top of a method.
Pattern checks instead of casts
object value = "text";
if (value is string text && text.Length > 3)
{
Console.WriteLine(text.ToUpper());
}
is with a type and a variable both tests and assigns in one step, and the variable is only in scope when the test succeeds. That removes the cast that would otherwise follow and the chance of an InvalidCastException.
if (value is int number)
{
Console.WriteLine(number * 2);
}
else if (value is not null)
{
Console.WriteLine($"other: {value.GetType().Name}");
}
is not null is the readable null test, and it works for any type without an overloaded ==.
Ternary and switch expressions
string label = total >= 1000m ? "large" : "small";
The conditional operator is an expression, so it can be assigned or passed. Keep it to one line; nesting it is where readability dies.
For more than two cases, a switch expression is clearer:
string size = total switch
{
>= 5000m => "bulk",
>= 1000m => "large",
_ => "small"
};
Bitwise, briefly
&, |, ^ and ~ operate on integers bit by bit, and << and >> shift. Flags enums use them:
[Flags]
enum Access { None = 0, Read = 1, Write = 2, Admin = 4 }
var permissions = Access.Read | Access.Write;
bool canRead = permissions.HasFlag(Access.Read);
HasFlag is clearer than a manual mask, and the [Flags] attribute makes ToString print the combination by name.
String concatenation and equality
+ concatenates strings and calls ToString on the other operand, which is convenient and easy to overuse inside loops. == on strings compares content, and Equals does the same; ReferenceEquals is the identity test when you actually need it.
+ on a string and a null treats null as empty; interpolation does the same. That is friendly and occasionally hides a missing value, so check before formatting when a blank would be ambiguous.
Writing if (name == null || name.Length == 0) when string.IsNullOrEmpty(name) says it once and cannot be got wrong. For input, IsNullOrWhiteSpace is usually the better check.
Given a nullable order object with a nullable customer and a nullable city, produce a display string that falls back to "unknown city", and a boolean saying whether the city is known.
Show solution
record Address(string City); record Customer(string Name, Address? Address); record Order(int Id, Customer? Customer); Order? order = new Order(1, new Customer("Ana", null)); string city = order?.Customer?.Address?.City ?? "unknown city"; bool known = order?.Customer?.Address?.City is not null; Console.WriteLine($"{city} ({known})"); The chain short-circuits at the first null, so no intermediate check is needed. ?? supplies the fallback, and is not null gives a boolean without comparing strings, which keeps "unknown" from being confused with a real city of that name.
Recap
- Integer division truncates; use
decimalfor money and cast only when you mean it. ?.and??make null handling explicit and short.- Prefer
ispattern checks to casts, andis not nullto== null.
Next, nullable reference types: what the annotations do and where they stop helping.
What does ? after a type mean?
Is ?? the same as the ternary operator?
Progress is saved in this browser only. No account, no email.