Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a method called processUserName that takes a string parameter userName. The method should:

  1. If userName is null, return "No user provided"
  2. If userName is empty or only whitespace, return "Invalid username"
  3. 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 null

Use 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 null

Try it yourself

using System;

class ProcessUserName
{
    public static string processUserName(string userName)
    {
        // Write your code here
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow