Guarding Against Nulls
Validation and patterns.
Guarding Against Nulls is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Guard Against Nulls?
A method that receives an unexpected null often crashes later with a confusing NullReferenceException deep in the call stack.
Guarding means checking arguments up front and failing clearly, so the error points straight at the real cause.
Classic Null Check
The simplest guard is an explicit check that throws an ArgumentNullException when a required argument is null.
This validates input at the boundary of your method, before any work begins.
void Save(string path)
{
if (path == null)
throw new System.ArgumentNullException(nameof(path));
System.Console.WriteLine(path);
}Use nameof
Pass nameof(path) rather than a hard-coded string. The exception then reports the exact parameter name, and it stays correct if you rename the parameter.
This makes debugging far easier when the exception is logged.
void Greet(string user)
{
if (user is null)
throw new System.ArgumentNullException(nameof(user));
System.Console.WriteLine("Hi " + user);
}ThrowIfNull Helper
Modern C# offers ArgumentNullException.ThrowIfNull(arg). It checks for null and throws with the correct parameter name automatically.
It is concise and the preferred guard style in current .NET code.
void Process(object data)
{
System.ArgumentNullException.ThrowIfNull(data);
System.Console.WriteLine("Processing");
}A Runnable Guard
This program shows a guard catching a null argument and reporting it cleanly instead of crashing later.
Run it to see the exception message naming the bad parameter.
using System;
class Program
{
static void Print(string text)
{
ArgumentNullException.ThrowIfNull(text);
Console.WriteLine(text);
}
static void Main()
{
try { Print(null); }
catch (ArgumentNullException ex) { Console.WriteLine(ex.ParamName); }
}
}Guard with ?? throw
You can combine assignment and guarding using ?? with throw. This validates and stores in one line.
It is a popular pattern in constructors when assigning to a field.
class Service
{
private readonly string _name;
public Service(string name)
=> _name = name ?? throw new System.ArgumentNullException(nameof(name));
}Empty Versus Null
For strings, null and empty are different problems. Use string.IsNullOrEmpty or string.IsNullOrWhiteSpace to catch both at once.
An ArgumentException (not ArgumentNullException) suits an empty-but-not-null value.
void SetName(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new System.ArgumentException("Name required", nameof(name));
}Guarding with Patterns
The is null and is not null patterns read clearly and cannot be fooled by overloaded equality operators.
Prefer is null over == null when a type might override ==.
object value = null;
if (value is null)
System.Console.WriteLine("It is null");
if (value is not null)
System.Console.WriteLine("Has value");Defaulting Instead of Throwing
Not every null is an error. Sometimes a sensible default is better than an exception.
Use ?? when null is acceptable, and throw only when the value is truly required.
string BuildPath(string folder)
{
folder ??= "/tmp";
return folder + "/file.txt";
}Nullable Reference Types Help
With nullable reference types enabled, the compiler warns when you might dereference a possibly-null value, catching bugs before runtime.
Declaring string (non-null) versus string? (nullable) documents your intent and guides the analyzer.
#nullable enable
string required = "ok";
string? optional = null;
System.Console.WriteLine(optional?.Length ?? 0);Guard Then Use Safely
Once you have guarded at the top of a method, the rest of the body can use the value without repeated null checks.
This program guards, then confidently uses the argument.
using System;
class Program
{
static int Length(string s)
{
ArgumentNullException.ThrowIfNull(s);
return s.Length;
}
static void Main()
{
Console.WriteLine(Length("hello"));
}
}Quick Check
Test your understanding of guarding against nulls.
Recap
Guard required arguments at the start of a method. Use ArgumentNullException.ThrowIfNull or ?? throw with nameof for clear errors.
Use string.IsNullOrWhiteSpace for empty strings, is null patterns for safe checks, and ?? when a default is acceptable instead of failing.
Frequently asked questions
Is the “Guarding Against Nulls” lesson free?
Yes — the full text of “Guarding Against Nulls” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Guarding Against Nulls”?
Validation and patterns. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Guarding Against Nulls” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Nullable Value Types
- Null-Conditional Operator
- Null-Coalescing Operators
- Guarding Against Nulls