Null-Conditional Operator
The ?.
operator is syntactic sugar to avoid verbose null checks. It’s also known as the Safe navigation operator.
Class used in the following example:
public class Person { public int Age { get; set; } public string Name { get; set; } public Person Spouse { get; set; } }
If an object is potentially null (such as a function that returns a reference type) the object must first be checked for null to prevent a possible NullReferenceException
. Without the null-conditional operator, this would look like:
Person person = GetPerson(); int? age = null; if (person != null) age = person.Age;
The same example using the null-conditional operator:
Person person = GetPerson(); var age = person?.Age; // 'age' will be of type 'int?', even if 'person' is not null
Chaining the Operator
The null-conditional operator can be combined on the members and sub-members of an object.
// Will be null if either `person` or `person.Spouse` are null int? spouseAge = person?.Spouse?.Age;
Combining with the Null-Coalescing Operator
The null-conditional operator can be combined with the null-coalescing operator to provide a default value:
// spouseDisplayName will be "N/A" if person, Spouse, or Name is null var spouseDisplayName = person?.Spouse?.Name ?? "N/A";
Table Of Contents
2
Literals
8
Null-Conditional Operators
18
Regex
19
DateTime
20
Arrays
22
Enum
23
Tuples
25
GUID
26
BigInteger
28
Looping
29
Iterators
30
IEnumerable
35
Dynamic type
37
Casting
41
Interfaces
47
Methods
52
Keywords
53
Recursion
57
Inheritance
58
Generics
62
Reflection
65
LINQ Queries
66
LINQ to XML
68
XmlDocument
69
XDocument
79
Diagnostics
80
Overflow
86
Properties
89
Events
93
Structs
94
Attributes
95
Delegates
97
Networking
102
Action Filters
103
Polymorphism
104
Immutability
105
Indexer
107
Stream
108
Timers
109
Stopwatches
110
Threading
112
Async Await
114
BackgroundWorker
117
Lock Statement
118
Yield Keyword
121
Func delegates
124
ICloneable
125
IComparable
127
Using SQLite
128
Caching
129
Code Contracts
136
Pointers
144
Hash Functions
146
Cryptography
148
C# Script
149
Runtime Compile
150
Interoperability
156
Contributors