Can string be null in C#?

In this article we're going to answer the question whether string can be null in C#.

Value vs reference types

The first thing that we need to understand is the difference between value and reference types.

Value types are used to directly represent a value and are stored on the stack for quick access.

They are usually small and lightweight.

Examples: byte, short, int, long.

Value types cannot be null.

Reference types are types with content placed on the heap and the stack contains only a reference to them.

Examples: string, int[], object

They're usually more complex than the value types.

Reference types can be null.

Since string is a reference type it can be null.

Nullable types

Since inserting null into a value type is impossible by default it was necessary to create nullable types to enable this type of behaviour.

You can use the question mark operator to create a nullable type out of a value type.

int -> int?

You can also create a nullable type out of a reference type.

string -> string?

It gives the IDE context information indicating that this given type is expected to contain null values.

You can use the null-forgiving operator (exclamation mark !) to signal to the IDE that a given variable of nullable type won't cotain null in a given scenario. It is usefull to prevent automatic warnings from the IDE.

Here is a small example using both null-forgiving operator and nullable types.

 
#nullable enable

using System;

public class Person {
    public Address? Address { get; set; }

    public Person(Address? address)
    {
        Address = address;
    }
}

public class Address {
    public string? Street { get; set; }

    public Address(string? street)
    {
        Street = street;
    }
}

public class Program
{
    public static void Main()
    {
        var person = new Person(new Address("street"));
        var street = person.Address!.Street;

        Console.WriteLine(street);
    }
}