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.
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?
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);Not measured yet 0
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?
<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.
string name = null; // warning CS8600: assigning null to non-nullablestring? nickname = null; // fine: declared as maybe-nullint len = nickname.Length; // warning CS8602: possible null dereferenceThe null-handling operators
| Operator | Meaning |
|---|---|
a?.B | a is null, result is null; otherwise a.B |
a?[i] | |
a ?? b | a if not null, else b |
a ??= b | b to a only if a is null |
a is null / a is not null | |
a! |
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");Unknown, 0 members
Guarding method arguments
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 requiredor constructors so objects can’t be created half-empty.Use TryXxx(out …)methods when “not found” is normal.
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
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(" "));RS ? ?
Remember
int?lets a value type hold null; checkHasValueor use??.With nullable reference types on, string?may be null andstringmust not be.Use ?.,??,??=andis not nullinstead of risky direct access.!only hides warnings; design APIs to avoid null where you can.