Overview
C# 6.0 has some interesting new features. The feature discussed in this post is null propogation. Null propogation allows you to check if a property exists and if it does, execute code. More information can be found here.
Details
Using the ?
symbol, we can see if the preceding variable holds a null. If it does, the chain stops and the value returned is null.
1
2
3
4
5
6
7
8
9
10
11
12
// Before
if (obj != null && obj.children != null) {
obj.children.Add( new Child() );
}
// In 6.0
if (obj?.children != null) {
obj.children.Add( new Child() );
}
// 1. Is obj == null? If yes, stop and the chain == null
// 2. Is children == null? If yes, stop and the chain == null