Null Checking Patterns
Part of the Logic & Flow section of Coddy's C# journey — lesson 33 of 66.
Null checking is an essential part of writing robust C# code. There are several patterns you can use to check for null values safely.
Let's explore some common null checking patterns:
First, the basic if-null check:
string name = null;
if (name == null)
{
Console.WriteLine("Name is null");
}
Another common pattern is the null-conditional operator (?.), which safely accesses members of potentially null objects:
string name = null;
int? length = name?.Length; // length will be null
The null-coalescing operator (??) provides a default value when an expression is null:
string name = null;
string displayName = name ?? "Unknown"; // displayName will be "Unknown"
You can also chain these patterns for more complex scenarios:
string name = null;
int length = (name ?? "").Length; // length will be 0
The string.IsNullOrWhiteSpace() method is a convenient way to check if a string is null, empty, or contains only whitespace characters — all in one call:
string name = null;
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Name is null, empty, or whitespace");
}
This is especially useful when you need to treat null, empty strings, and whitespace-only strings the same way. For example:
string name1 = null;
string name2 = "";
string name3 = " ";
// All three will print the message
if (string.IsNullOrWhiteSpace(name1)) Console.WriteLine("name1 is null/empty/whitespace");
if (string.IsNullOrWhiteSpace(name2)) Console.WriteLine("name2 is null/empty/whitespace");
if (string.IsNullOrWhiteSpace(name3)) Console.WriteLine("name3 is null/empty/whitespace");
Note that string.IsNullOrWhiteSpace() is different from a plain null check — it also catches empty strings and strings that only contain spaces, tabs, or other whitespace characters.
Challenge
EasyCreate a method called processUserName that takes a string parameter userName. The method should:
- If
userNameis null, return "No user provided" - If
userNameis empty or only whitespace, return "Invalid username" - Otherwise, return "Welcome, [userName]!" where [userName] is the actual username
Remember to use appropriate null checking patterns.
Try it yourself
using System;
class ProcessUserName
{
public static string processUserName(string userName)
{
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety