Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Nullable Types

C# Nullable Types (Nullable)

In C#,int、float、bool、DateTime are allvalue types, which by default must have a value and cannot be null:

int a = null;  // 编译错误:无法将 null 转换为 int

Nullable Types solve this problem - they give value types an extra "no value" state (i.e. null), which is very practical in scenarios where data may be missing, such as database fields and API return values.

Declaration is simple: add a ?:

int? a = null;  // 合法

int? b = 42;    // 合法

Here, int? Is Nullable syntax sugar (shorthand) after the type; the two are completely equivalent:

Nullable a = null;   // 完整写法

int? a = null;              // 简写,效果相同

The figure below shows how nullable types work in memory - they use an extra boolean flag to record "whether there is a value":

Nullable memory structure of int (ordinary value type) Value: 42 4 bytes, always has a value to wrap Nullable(nullable type) HasValue Value 1 byte 4 bytes 5+ bytes in total int? x = 42; true ✓ 42 HasValue = true,Value = 42 int? y = null; false ✗ None HasValue = false, accessing Value throws an exception

The Difference Between Single Question Mark ? and Double Question Mark ??

In C#, two operators related to nullable types are often used together but have completely different meanings:

operator Name Purpose Example
? Nullable type modifier allows value types to be null null int? i = 3; is equivalent to Nullable i = new Nullable(3);
?? Null-Coalescing Operator provides a default value when the variable is null null int result = i ?? 0;

A simple comparison:

int i;     // 普通值类型,默认值为 0,永远不能是 null

int? ii;   // 可空类型,默认值为 null


Declaration and Assignment of Nullable Types

Declaration syntax

?  = null;

For example:

int? age = null;

double? temperature = 36.6;

bool? isActive = new bool?();   // 显式构造,默认为 null

DateTime? birthday = null;

Nullable can represent the normal range of its underlying value type, plus an additional null value. For example Nullable can be -2,147,483,648 to 2,147,483,647 any integer between them, or null。

Complete example

Example

using

System

;

namespace

NullableDemo

{

   

class

Program

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

// Declare nullable variables of different types

           

int

?

num1

=

null

;

           

int

?

num2

=

45

;

           

double

?

num3

=

new

double

?

(

)

;

 

// null

           

double

?

num4

=

3.14157

;

           

bool

?

boolVal

=

new

bool

?

(

)

;

   

// null

           

// Display values (null displays as an empty string)

            Console

.

WriteLine

(

$

"num1 = {num1 ?? 0}"

)

;

       

// 0

            Console

.

WriteLine

(

$

"num2 = {num2 ?? 0}"

)

;

       

// 45

            Console

.

WriteLine

(

$

"num3 = {num3 ?? 0.0}"

)

;

     

// 0

            Console

.

WriteLine

(

$

"num4 = {num4 ?? 0.0}"

)

;

     

// 3.14157

            Console

.

WriteLine

(

$

"boolVal = {boolVal}"

)

;

       

// (empty)

       

}

   

}

}

Output result:

num1 = 0

num2 = 45

num3 = 0

num4 = 3.14157

boolVal =


Null-Coalescing Operator (??)

?? operator provides afallback default value. When the left side is not null , it returns the left-side value; otherwise, it returns the right-side value:

<表达式1> ?? <表达式2>

Starting from C# 8.0, you can also use ??=(null-coalescing assignment operator), which assigns a value only when the variable is null null:

int? x = null;

x ??= 10;   // x 为 null,赋值为 10

x ??= 20;   // x 已有值 10,不再赋值

Example

using

System

;

namespace

NullableDemo

{

   

class

Program

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

double

?

num1

=

null

;

           

double

?

num2

=

3.14157

;

           

// ?? provides a default value

           

double

result1

=

num1

??

5.34

;

 

// num1 is null → returns 5.34

           

double

result2

=

num2

??

5.34

;

 

// num2 has a value → returns 3.14157

            Console

.

WriteLine

(

$

"num1 ?? 5.34 = {result1}"

)

;

 

// 5.34

            Console

.

WriteLine

(

$

"num2 ?? 5.34 = {result2}"

)

;

 

// 3.14157

           

// Chained use: provide multiple alternative values

           

int

?

a

=

null

;

           

int

?

b

=

null

;

           

int

?

c

=

42

;

           

int

value

=

a

??

b

??

c

??

0

;

   

// Try in sequence, finally get 42

            Console

.

WriteLine

(

$

"a ?? b ?? c ?? 0 = {value}"

)

;

// 42

       

}

   

}

}

Output result:

num1 ?? 5.34 = 5.34

num2 ?? 5.34 = 3.14157

a ?? b ?? c ?? 0 = 42


Common Properties and Methods of Nullable Types

members Description Example
.HasValue Determine whether a variable has a value (returns bool) if (num.HasValue) { ... }
.Value Get the actual value (throws if null throws InvalidOperationException) int x = num.Value;
.GetValueOrDefault() Safely get the value; if it is null null returns the type's default value (e.g. 0) num.GetValueOrDefault()
.GetValueOrDefault(T) Safely get the value; if it is null null returns the specified default value num.GetValueOrDefault(100)
?? Null-coalescing operator (syntax sugar, equivalent to GetValueOrDefault) int result = num ?? 100;

Example

using

System

;

namespace

NullableDemo

{

   

class

Program

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

int

?

num

=

null

;

           

// HasValue + Value (traditional approach)

           

if

(

num

.

HasValue

)

                Console

.

WriteLine

(

$

"Value is: {num.Value}"

)

;

           

else

                Console

.

WriteLine

(

"num has no value"

)

;

           

// Safely get the default value

            Console

.

WriteLine

(

num

.

GetValueOrDefault

(

)

)

;

     

// 0

            Console

.

WriteLine

(

num

.

GetValueOrDefault

(

99

)

)

;

   

// 99

            Console

.

WriteLine

(

num

??

99

)

;

                   

// 99 (equivalent approach)

           

// ⚠ Note: accessing .Value directly throws an exception

           

// int x = num.Value;  // InvalidOperationException!

       

}

   

}

}


Practical Application Scenarios

Nullable types are very common in real development, especially when handling data that may be missing:

Database Field Mapping

Fields in a database are allowed to be NULL, and nullable types can map to them precisely:

User ID Age Is Active
1 28 true
2 null false
int? age = GetUserAgeFromDB(userId: 2);



// Safely handle null

string display = age.HasValue

    ? $"用户年龄:{age.Value}"

    : "年龄未知";



// or a more concise way

string display2 = $"用户年龄:{age ?? 0}";

Optional Parameters and Configuration

// 配置项可能未设置

int? timeout = GetConfigValue("timeout");

int actualTimeout = timeout ?? 30;  // 未设置时使用默认值 30 秒

Chained Null Checks (C# 6.0+)

// 使用 ?. 运算符安全访问可能为 null 的对象

string? name = user?.Address?.City?.Name;

// If any of user, Address, or City is null, the result is null, and no exception is thrown


Summary

Function Example Description
Define a nullable type int? x = null; is equivalent to Nullable
Check whether it has a value x.HasValue Return true or false
Get the value (unsafe) x.Value if null null throws InvalidOperationException
get the default value x ?? 0 if null null returns the right-side value
get the specified default value x.GetValueOrDefault(10) if null null returns 10
Null-coalescing assignment x ??= 10 is evaluated only when x is null assign when null (C# 8.0+)
Safe navigation access user?.Name If user is null then returns null(C# 6.0+)

C# 8.0's "Nullable Reference Types"

Starting from C# 8.0, Nullable Reference Types, which is a different mechanism from thenullable value typesintroduced in this article:

Comparison Item nullable value types Nullable reference types
Example int? string?
Applies To Value types (int、bool、struct etc.) Reference types (string、class, arrays, etc.)
Implementation implemented at runtime via the Nullable struct compiler static analysis, does not change runtime behavior
Default state Always present (since C# 1.0) Must be enabled in the project enable
null Check Using .HasValue Decision Compiler issues warnings (not errors)

Nullable reference types are a compile-time safety-checking tool - they do not change the program's runtime behavior, but they issue compiler warnings in places where the code may produce NullReferenceException null, helping you discover potential problems during development.