We have seen how reference types differ from value types in how they are stored in memory and how to store primitive values like numbers in struct variables. But what if a variable does not yet have a value? How can we indicate that? C# has the concept of a null value, which can be used to indicate that a variable has not been set.

Making a value type nullable

By default, value types like int and DateTime must always have a value, hence their name. Sometimes, for example, when reading values stored in a database that allows empty, missing, or null values, it is convenient to allow a value type to be null. We call this a nullable value type. We can enable this by adding a question mark as a suffix to the type when declaring a variable. Let’s see an example:

Step 1: Use your preferred coding tool to add a new Console App or console project named NullHandling to the Chapter06 workspace or solution.

  • In Visual Studio Code, select NullHandling as the active OmniSharp project.

  • In Visual Studio 2022, set NullHandling as the startup project.

Step 2: In NullHandling.csproj, add an <ItemGroup> to globally and statically import the System.Console class.

Step 3: In Program.cs, delete the existing statements, and then add statements to declare and assign values, including null, to int variables, one suffixed with ? and one not, as shown in the following code:

Get hands-on with 1400+ tech skills courses.