Can string be null in C#?

Опубликовано: 19 Июнь 2026
на канале: NET Programmer
777
5

Article: https://net-programmers.com/Articles/...

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, 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 to int?

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

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