Skip to content

Category: C#

Can C# struct be assigned to null?

Reading Time: 3 minutes

Types in C# are divided into two groups:

  • reference types (classes);
  • value types (primitives, structs).

The variables of the first group contain the references to the object instances. That is why these variables can be null, means pointing to nothing, or not initialized. But as for the latter group, the variables of it are stored directly as values without references. In this case, null cannot be assigned.

At the same time, C# allows to wrap value types into Nullable struct to make them “optional” and capable for later initialization.

This can be done in the following way:

Nullable<int> value = null;

besides, there is a short notation for the same part of code:

int? value = null;

Nice. But wait a second, Nullable is a struct and structs are value types. How come that it can be assigned to null?

Leave a Comment
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.