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 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 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.

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