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

C# Null Conditional Operator

C# Null Conditional Operator

C# Decision C# Decision Making

In C# programming, handling null values is a common but error-prone task.

Traditional null null checks are often verbose and tedious, while the Null Conditional Operator(?. and ?[]introduced in C# 6.0 greatly simplifies this process.

The Null Conditional Operator is syntactic sugar introduced in C# 6.0 that allows developers to check whether an object is nullbefore accessing its members or elements. If the object is null, the result of the entire expression is null, without throwing an NullReferenceException。

Basic Syntax

Syntax Description
a?.b If both the a if not null, access a.b; otherwise return null
a?.Method() If both the a if not null, call the method; otherwise do nothing
a?[i] If both the a if not null, access the index; otherwise return null

Why do we need the Null Conditional Operator?

The Problem with Traditional null Checks

Before the Null Conditional Operator appeared, developers had to write verbose null check code:

Example

// Traditional approach - tedious null checks

string

name

=

null

;

if

(

person

!=

null

)

{

   

if

(

person

.

Address

!=

null

)

   

{

       

if

(

person

.

Address

.

City

!=

null

)

       

{

            name

=

person

.

Address

.

City

.

Name

;

       

}

   

}

}

This kind of code is not only verbose but also error-prone and less readable.

Advantages of the Null Conditional Operator

With the Null Conditional Operator, the same logic can be simplified to:



// Using the Null Conditional Operator - concise and clear

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

If any link in the chain is null, the entire expression returns null, without throwing an exception.


Detailed Syntax Explanation

1. Member Access Operator ?.

?. operator is used to safely access members of an object (properties, methods, fields).

Accessing Attributes

Example

class

Person

{

   

public

string

Name

{

get

;

set

;

}

   

public

Address Address

{

get

;

set

;

}

}

class

Address

{

   

public

string

City

{

get

;

set

;

}

}

// Safely access a property

Person person

=

null

;

string

cityName

=

person

?.

Address

?.

City

;

 

// Returns null without throwing an exception

Call the method

Example

class

Calculator

{

   

public

int

Add

(

int

a,

int

b

)

=>

a

b

;

}

Calculator calc

=

null

;

int

?

result

=

calc

?.

Add

(

5

,

3

)

;

 

// Returns null without throwing an exception

Access a field

Example

class

DataContainer

{

   

public

string

Value

;

}

DataContainer container

=

null

;

string

value

=

container

?.

Value

;

 

// Returns null without throwing an exception

2. Element Access Operator ?[]

?[] operator is used to safely access elements of an array or collection.

Accessing Array Elements

Example

int

[

]

numbers

=

null

;

int

?

firstNumber

=

numbers

?

[

0

]

;

 

// Returns null without throwing an exception

numbers

=

new

int

[

]

{

1

,

2

,

3

}

;

firstNumber

=

numbers

?

[

0

]

;

 

// returns 1

Access a dictionary element

Example

Dictionary

<

string

,

string

dictionary

=

null

;

string

value

=

dictionary

?

[

"key"

]

;

 

// Returns null without throwing an exception

dictionary

=

new

Dictionary

<

string

,

string

{

[

"key"

]

=

"value"

}

;

value

=

dictionary

?

[

"key"

]

;

 

// Returns "value"


Combined Use with Other Operators

operator Name Purpose Example Return Value
? Nullable type declaration declares a value type that can be null int? x = null; null
?? Null coalescing operator returns the right operand if the left is null a ?? b b
?. Null Conditional Operator safely access a member a?.b null or the value of b
?[] Null conditional indexing operator safely access an array or collection a?[i] null or the element
?: Conditional (ternary) operator returns different values based on a condition a ? b : c b or c

1. With the Null Coalescing Operator ?? combined with

The null-conditional operator is often used together with the null-coalescing operator ?? to provide a default value:

Person person = null;



// Provide default value

string cityName = person?.Address?.City ?? "未知城市";

Console.WriteLine(cityName);  // 输出: 未知城市



person = new Person { Address = new Address { City = "Beijing" } };

cityName = person?.Address?.City ?? "未知城市";

Console.WriteLine(cityName);  // 输出: 北京

Example

using

System

;

class

Address

{

   

public

string

City

{

get

;

set

;

}

}

class

Person

{

   

public

string

Name

{

get

;

set

;

}

   

public

Address Address

{

get

;

set

;

}

   

public

void

SayHello

(

)

   

{

        Console

.

WriteLine

(

$

"Hello, I am {Name}"

)

;

   

}

}

class

Program

{

   

static

void

Main

(

)

   

{

        Person person

=

null

;

       

// Safely access a property

        Console

.

WriteLine

(

person

?.

Name

??

"Unnamed User"

)

;

       

// Safely access nested properties

        Console

.

WriteLine

(

person

?.

Address

?.

City

??

"Unknown city"

)

;

       

// Safely call methods

        person

?.

SayHello

(

)

;

       

// Safely access arrays

       

int

[

]

arr

=

null

;

        Console

.

WriteLine

(

arr

?

[

0

]

??

1

)

;

   

}

}

Output:

未命名用户

未知城市

-1

2. With the Conditional Operator ?: combined with

Example

Person person

=

null

;

string

displayName

=

person

?.

Name

??

(

person

!=

null

?

"Anonymous user"

:

"User does not exist"

)

;

3. Use in LINQ Queries

Example

List

<

Person

people

=

new

List

<

Person

{

new

Person

{

Name

=

"Zhang San"

, Address

=

new

Address

{

City

=

"Beijing"

}

}

,

   

new

Person

{

Name

=

"Li Si"

, Address

=

null

}

,

   

null

}

;

// Safely access properties that may be null

var

cities

=

people

   

.

Where

(

p

=>

p

?.

Address

?.

City

!=

null

)

   

.

Select

(

p

=>

p

.

Address

.

City

)

   

.

ToList

(

)

;


Practical Application Scenarios

Scenario 1: Data Binding and UI Development

Example

// Safely bind data in WPF or ASP.NET

public

string

DisplayAddress

=>

$

"{Person?.Address?.City ?? "

Unknown City

"} - {Person?.Address?.Street ?? "

Unknown Street

"}"

;

// Safely call methods

button

.

Click

+=

(

s, e

)

=>

{

    viewModel

?.

SaveCommand

?.

Execute

(

null

)

;

}

;

Scenario 2: API Response Handling

Example

public

class

ApiResponse

<

T

{

public

T Data

{

get

;

set

;

}

   

public

string

Error

{

get

;

set

;

}

}

public

class

User

{

   

public

string

Name

{

get

;

set

;

}

   

public

Profile Profile

{

get

;

set

;

}

}

public

class

Profile

{

   

public

string

AvatarUrl

{

get

;

set

;

}

}

// Safely handle API responses

ApiResponse

<

User

response

=

GetUserFromApi

(

)

;

string

avatarUrl

=

response

?.

Data

?.

Profile

?.

AvatarUrl

??

"default-avatar.png"

;

Scenario 3: Configuration Reading

Example

public

class

AppConfig

{

   

public

DatabaseConfig Database

{

get

;

set

;

}

}

public

class

DatabaseConfig

{

   

public

string

ConnectionString

{

get

;

set

;

}

   

public

int

?

Timeout

{

get

;

set

;

}

}

// Safely read configuration

AppConfig config

=

LoadConfiguration

(

)

;

string

connectionString

=

config

?.

Database

?.

ConnectionString

??

"DefaultConnection"

;

int

timeout

=

config

?.

Database

?.

Timeout

??

30

;


Considerations and Best Practices

1. Return Value Types

When using the null-conditional operator, pay attention to the return type of the expression:

Example

Person person

=

new

Person

{

Name

=

"Zhang San"

}

;

// For value types, returns Nullable

int

?

nameLength

=

person

?.

Name

?.

Length

;

 

// The type is int?

// For reference types, returns the type itself

string

name

=

person

?.

Name

;

 

// The type is string

2. Avoid Overuse

Although the null-conditional operator is convenient, it should not be overused:

Example

// Not recommended - overused and hard to understand

var

result

=

obj1

?.

Property1

?.

Method1

(

)

?.

Property2

??

defaultValue

;

// Recommended - break it down appropriately to improve readability

var

temp1

=

obj1

?.

Property1

;

var

temp2

=

temp1

?.

Method1

(

)

;

var

result

=

temp2

?.

Property2

??

defaultValue

;

3. Performance considerations

The null-conditional operator performs on par with explicit null null checks, but chained calls create temporary variables:

Example

// These two approaches have comparable performance

// Approach 1: Traditional check

if

(

person

!=

null

&&

person

.

Address

!=

null

)

{

   

return

person

.

Address

.

City

;

}

// Approach 2: Null-conditional operator

return

person

?.

Address

?.

City

;

4. Combined with Event Invocation

The null-conditional operator is especially suitable for event invocation:

Example

// Traditional way

public

event

EventHandler SomethingHappened

;

protected

virtual

void

OnSomethingHappened

(

)

{

   

if

(

SomethingHappened

!=

null

)

   

{

        SomethingHappened

(

this

, EventArgs

.

Empty

)

;

   

}

}

// Use the null-conditional operator - more concise

protected

virtual

void

OnSomethingHappened

(

)

{

    SomethingHappened

?.

Invoke

(

this

, EventArgs

.

Empty

)

;

}


Practical Exercise

Exercise 1: Refactor Code

Refactor the following traditional null null-check code to use the null-conditional operator:

Example

// Original code

public

string

GetUserEmail

(

User user

)

{

   

if

(

user

!=

null

)

   

{

       

if

(

user

.

Profile

!=

null

)

       

{

           

if

(

user

.

Profile

.

ContactInfo

!=

null

)

           

{

               

return

user

.

Profile

.

ContactInfo

.

Email

;

           

}

       

}

   

}

   

return

"No email information"

;

}

// Your refactored code

public

string

GetUserEmail

(

User user

)

{

   

return

user

?.

Profile

?.

ContactInfo

?.

Email

??

"No email information"

;

}

Exercise 2: Handle Collection Data

Example

public

class

Order

{

   

public

List

<

OrderItem

Items

{

get

;

set

;

}

   

public

Customer Customer

{

get

;

set

;

}

}

public

class

OrderItem

{

   

public

Product Product

{

get

;

set

;

}

   

public

int

Quantity

{

get

;

set

;

}

}

public

class

Product

{

   

public

string

Name

{

get

;

set

;

}

   

public

decimal

Price

{

get

;

set

;

}

}

public

class

Customer

{

   

public

string

Name

{

get

;

set

;

}

}

// Write a method that safely gets the name of the first item in an order

public

string

GetFirstProductName

(

Order order

)

{

   

return

order

?.

Items

?.

FirstOrDefault

(

)

?.

Product

?.

Name

??

"No item information"

;

}

Exercise 3: Comprehensive Application

Example

// Create a complete example demonstrating the use of the null-conditional operator in a real project

public

class

ShoppingCart

{

   

public

List

<

CartItem

Items

{

get

;

set

;

}

   

public

decimal

?

CalculateTotal

(

)

   

{

       

return

Items

?.

Sum

(

item

=>

item

?.

Product

?.

Price

item

?.

Quantity

)

??

0

;

   

}

}

public

class

CartItem

{

   

public

Product Product

{

get

;

set

;

}

   

public

int

?

Quantity

{

get

;

set

;

}

}

C# Decision C# Decision Making