Skip to main content

How to Use a Nullable Value Type like int? in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

int? rating = null; declares a number that can also be null, for a value nobody has given yet. HasValue tells you whether it holds a number, and GetValueOrDefault() gives you a number either way.

A plain int always holds a number, so it can't say "no value yet". Add ? after the type and it can. Microsoft's reference: A nullable value type T? represents all values of its underlying value type T and an additional null value. And when to use one: Typically, use a nullable value type when you need to represent the undefined value of an underlying value type.

Syntax​

Syntax
<Type>? <name> = null;
<Type>? <name> = <value>;

bool <hasIt> = <name>.HasValue;
<Type> <it> = <name>.Value;
<Type> <it> = <name>.GetValueOrDefault();
<Type> <it> = <name>.GetValueOrDefault(<fallback>);
PartWhat it is
<Type>?Any value of <Type>, or null. <Type> is a value type, such as int, bool, double or an enum
<name>.HasValuetrue when it holds a value, false when it's null
<name>.ValueThe value. When there's none, it throws an InvalidOperationException
<name>.GetValueOrDefault()The value, or the default of <Type> when it's null, such as 0 for int
<name>.GetValueOrDefault(<fallback>)The value, or <fallback> when it's null

The reference on Value: If HasValue is false, the Value property throws an InvalidOperationException.

The Example​

A console app called NullableValue keeps a rating from 1 to 5 in an int?, first before anyone gives one and then after someone gives a 4. Then it does the same with a clothing size, to show that an enum can be nullable too.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n NullableValue
cd NullableValue
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NullableValue/NullableValue.csproj:
Determining projects to restore...
Restored /Users/you/source/NullableValue/NullableValue.csproj (in 40 ms).
Restore succeeded.

dotnet new console -n NullableValue creates a folder named NullableValue with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or NullableValue.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the rating that nobody has given yet:

Program.cs (no rating yet)
// A rating from 1 to 5 that nobody has given yet: int? can hold an int or null.
int? rating = null;
Console.WriteLine($"Has a rating: {rating.HasValue}");
Console.WriteLine($"GetValueOrDefault(): {rating.GetValueOrDefault()}");
Console.WriteLine($"GetValueOrDefault(3): {rating.GetValueOrDefault(3)}");

int? is an int that can also be null, and null here means "no rating yet". HasValue tells you which one you have. GetValueOrDefault() returns the default of int, which is 0, and GetValueOrDefault(3) returns the 3 you pass in.

Then the rating of 4:

Program.cs (a rating of 4)
// Someone gives a rating of 4: now HasValue is true and Value is 4.
rating = 4;
Console.WriteLine($"Has a rating: {rating.HasValue}");
Console.WriteLine($"Value: {rating.Value}");

An int goes into an int? without a cast. Value returns the number inside, so read it only when HasValue is true.

Last, a nullable enum:

Program.cs (a nullable enum)
// An enum is a value type too, so Size? holds a Size or null.
Size? size = null;
Console.WriteLine($"Has a size: {size.HasValue}");
size = Size.Large;
Console.WriteLine($"Size: {size.Value}");

enum Size { Small, Medium, Large }

The enum line at the end declares Size with three named values. An enum is a value type, so Size? works the same way as int?.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Has a rating: False
GetValueOrDefault(): 0
GetValueOrDefault(3): 3
Has a rating: True
Value: 4
Has a size: False
Size: Large

macOS-style terminal window titled Terminal — NullableValue showing dotnet run printing Has a rating: False, GetValueOrDefault(): 0, GetValueOrDefault(3): 3, Has a rating: True, Value: 4, Has a size: False and Size: Large

Before anyone gave a rating, HasValue was False, GetValueOrDefault() returned 0 and GetValueOrDefault(3) returned 3. After rating = 4, HasValue was True and Value returned 4. The nullable Size worked the same way: no size first, then Large.

The Complete File​

macOS-style code window titled Program.cs — NullableValue showing an int? rating set to null and read with HasValue and GetValueOrDefault, then set to 4 and read with Value, a nullable Size enum set to null and then to Large, and the Size enum with Small, Medium and Large

Program.cs
// A rating from 1 to 5 that nobody has given yet: int? can hold an int or null.
int? rating = null;
Console.WriteLine($"Has a rating: {rating.HasValue}");
Console.WriteLine($"GetValueOrDefault(): {rating.GetValueOrDefault()}");
Console.WriteLine($"GetValueOrDefault(3): {rating.GetValueOrDefault(3)}");

// Someone gives a rating of 4: now HasValue is true and Value is 4.
rating = 4;
Console.WriteLine($"Has a rating: {rating.HasValue}");
Console.WriteLine($"Value: {rating.Value}");

// An enum is a value type too, so Size? holds a Size or null.
Size? size = null;
Console.WriteLine($"Has a size: {size.HasValue}");
size = Size.Large;
Console.WriteLine($"Size: {size.Value}");

enum Size { Small, Medium, Large }

What a New int? Holds​

A nullable value type's default value is null. The reference: The default value of a nullable value type represents null. It's an instance whose Nullable<T>.HasValue property returns false. So a new array of int? values starts with null in every place. This check makes an array of three, sets another int? to default, reads HasValue on both and prints the second one:

Checking the default
// A new array of int? starts with null in every place.
int?[] ratings = new int?[3];
Console.WriteLine($"ratings[0].HasValue: {ratings[0].HasValue}");

// default for an int? is null too.
int? unset = default;
Console.WriteLine($"unset.HasValue: {unset.HasValue}");

// A null int? prints as an empty string.
Console.WriteLine($"Printed: [{unset}]");
Output
ratings[0].HasValue: False
unset.HasValue: False
Printed: []

Both were null, and a null int? printed as an empty string between the brackets.

Common Mistakes​

MistakeWhat happensDo this instead
Reading Value without checking HasValueThe build warned warning CS8629: Nullable value type may be null., and the run threw InvalidOperationException: Nullable object must have a value.Check HasValue first, or use GetValueOrDefault()
Putting an int? into an interror CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)Use GetValueOrDefault() or GetValueOrDefault(<fallback>). A cast such as (int)rating compiles, but with null it threw the same Nullable object must have a value.
Assigning null to a plain interror CS0037: Cannot convert null to 'int' because it is a non-nullable value typeDeclare it as int?

FAQ​

Is int? the same as Nullable<int>?​

Yes. The reference: You can refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable<T> or T?. A check printed Same type: True for typeof(int?) == typeof(Nullable<int>).

Why not use 0 or -1 for "no rating"?​

Because they're numbers, and nothing stops the rest of the code from treating them as real ratings. With int?, "no rating" is null, and the code has to deal with it through HasValue, Value or GetValueOrDefault().

Conclusion​

Add ? after a value type, as in int? or Size?, when a value can be missing. Check HasValue before you read Value, or call GetValueOrDefault() to get a number back either way, with no exception.

Additional Resources​