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 checks whether a string is null, empty, or contains only whitespace characters. It is a convenient way to validate string input in a single call:
string name = null;
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("No name provided"); // this will print
}
string blank = " ";
if (string.IsNullOrWhiteSpace(blank))
{
Console.WriteLine("Blank name provided"); // this will also print
}
Use string.IsNullOrWhiteSpace() when you want to treat null, empty strings, and whitespace-only strings as equivalent invalid input.
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.
Cheat sheet
Use == null for basic null checking:
if (name == null)
{
Console.WriteLine("Name is null");
}Use the null-conditional operator ?. to safely access members:
int? length = name?.Length; // length will be null if name is nullUse the null-coalescing operator ?? to provide default values:
string displayName = name ?? "Unknown";Use string.IsNullOrWhiteSpace() to check for null, empty, or whitespace-only strings:
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Name is null, empty, or whitespace");
}Chain operators for complex scenarios:
int length = (name ?? "").Length; // length will be 0 if name is nullTry 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