<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Working with data
All lessons in this course

Lesson 34 of 60 13 minIntermediate

Nullable types and null safety

Represent “no value” on purpose, avoid NullReferenceException with ?. ?? and pattern checks, and let the compiler warn you before your users crash.

Tony Hoare, who invented null references, called them his “billion-dollar mistake”: NullReferenceException is the most common crash in C# programs. Modern C# gives you tools to say where null is allowed and to handle it safely.

Nullable value types: int?

NullableInt.cs
int? measured = null;        // int? = Nullable<int>: a number OR nulldouble? deflection = 12.5; if (measured.HasValue)    Console.WriteLine(measured.Value);else    Console.WriteLine("Not measured yet"); int shown = measured ?? 0;   // fallback when nullConsole.WriteLine(shown);
Output
Not measured yet
0

Value types like int can never be null on their own. Add ? when “unknown” or “not entered” is a real possibility, like an optional database column.

Nullable reference types: string?

New projects have nullable reference types turned on (<Nullable>enable</Nullable> in the .csproj). Then string means “never null” and string? means “may be null”, and the compiler warns when you might use a null.

Warnings.cs
string name = null;          // warning CS8600: assigning null to non-nullablestring? nickname = null;     // fine: declared as maybe-nullint len = nickname.Length;   // warning CS8602: possible null dereference

The null-handling operators

Interactive

Handling null safely

string? name =int? stock =
name.Length4Fine while name holds a string.
name?.Length4?. (null-conditional): if name is null, the whole expression becomes null instead of crashing.
name?.Length ?? 04?? (null-coalescing): use the right side when the left is null.
name ?? "Guest""Ravi"A default value in one expression.
name ??= "Guest";name unchanged??= assigns only when the variable is null.
if (name is not null) …runsInside the if, the compiler knows name isn’t null: no warnings.
name!.Length4! (null-forgiving) only silences the warning. It doesn’t make null safe. Use it only when you are certain.
stock.HasValuetrueint? (Nullable<int>) can hold a number or null.
stock.Value12Reading .Value of an empty nullable throws.
stock.GetValueOrDefault()12The type’s default (0) when null. Same as stock ?? 0.
OperatorMeaning
a?.Bif a is null, result is null; otherwise a.B
a?[i]null-safe indexing
a ?? ba if not null, else b
a ??= bassign b to a only if a is null
a is null / a is not nullthe clearest null check
a!“trust me, it isn’t null”: silences the warning, adds no safety
Chain.cs
Project? project = LoadProject("tower.json"); // Each ?. stops safely at the first null in the chainstring city = project?.Site?.Address?.City ?? "Unknown";int beams = project?.Members?.Count ?? 0; Console.WriteLine($"{city}, {beams} members");
Output
Unknown, 0 members

Guarding method arguments

Guards.cs
public void Export(Model model, string path){    ArgumentNullException.ThrowIfNull(model);              // .NET 6+    ArgumentException.ThrowIfNullOrWhiteSpace(path);       // .NET 7+    // … safe to use model and path from here on}

Avoiding null in your design

  • Return an empty collection, never null, from methods that return lists.
  • Initialise properties: public List<Beam> Beams { get; } = new();.
  • Use required or constructors so objects can’t be created half-empty.
  • Use TryXxx(out …) methods when “not found” is normal.
Quick check

With string? s = null;, what is s?.Length ?? -1?

Quick check

What does the ! in s!.Length do at run time?

Practice

Write static string Initials(string? fullName) that returns the uppercase initials ("ravi selva" → "RS"), or "?" when the input is null, empty or only spaces.

Show the solution
Solution.cs
static string Initials(string? fullName){    if (string.IsNullOrWhiteSpace(fullName)) return "?";     var parts = fullName.Split(' ', StringSplitOptions.RemoveEmptyEntries);    var sb = new System.Text.StringBuilder();    foreach (string p in parts) sb.Append(char.ToUpper(p[0]));    return sb.ToString();} Console.WriteLine(Initials("ravi selva"));Console.WriteLine(Initials(null));Console.WriteLine(Initials("   "));
Output
RS
?
?

Remember

  • int? lets a value type hold null; check HasValue or use ??.
  • With nullable reference types on, string? may be null and string must not be.
  • Use ?., ??, ??= and is not null instead of risky direct access.
  • ! only hides warnings; design APIs to avoid null where you can.
0 of 60 lessons completed