Menu
Coddy logo textTech

Null Reference Basics

Part of the Logic & Flow section of Coddy's C# journey — lesson 31 of 66.

In C#, a null reference represents the absence of an object. Understanding how to work with null values is essential for writing robust code.

Declare a reference type variable (like string) without assigning a value:

string name = null;

The variable 'name' now holds a null reference, which means it doesn't point to any object in memory.

Trying to use a null reference without checking can cause runtime errors:

string name = null;
// This will throw a NullReferenceException
int length = name.Length;

You can check if a reference is null before using it:

string name = null;
if (name != null)
{
    // Safe to use name here
    int length = name.Length;
}

You can also assign a non-null value to the variable:

string name = null;
name = "John";
// Now it's safe to use name
int length = name.Length; // length will be 4
challenge icon

Challenge

Easy

Create a method called ProcessName that takes a string parameter called name. The method should:

  1. Check if the name is null
  2. If the name is null, print: "Name is null"
  3. If the name is not null, print: "Name length is X" (where X is the length of the name)

Cheat sheet

A null reference represents the absence of an object in C#.

Declare a reference type variable with null:

string name = null;

Using null references without checking causes runtime errors:

string name = null;
// This will throw a NullReferenceException
int length = name.Length;

Check for null before using:

string name = null;
if (name != null)
{
    // Safe to use name here
    int length = name.Length;
}

Assign a non-null value to make it safe to use:

string name = null;
name = "John";
int length = name.Length; // length will be 4

Try it yourself

using System;

class Program
{
    public static void ProcessName(string name)
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        string input = Console.ReadLine();
        
        // Convert "null" string to actual null
        string name = input.ToLower() == "null" ? null : input;
        
        ProcessName(name);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow