Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 21 / 68

Writing Null-Safe Code (the ?? operator)

In this lesson you will learn null-safe code in C# using the ?? operator, and how to avoid errors when a value has not been set. This is for anyone searching for "C# null-coalescing operator how to use".

?? (the null-coalescing operator) uses the right-hand value only when the left-hand side is null. It is the basic way to work safely with a variable that may or may not hold a value.

The sample code writes address ?? "No address set" so that a replacement string is shown when address is null. You can see that name, which does hold a value, is used as-is.

A common stumbling block for beginners is using a value that is still null and hitting an error. C# also offers nullable reference types, which manage nullability more strictly through the type system and raise your safety further.

In real-world development, the related ??= assignment operator is also common: it assigns a value only when the variable is null.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)