Null propagating operator in C#

gpeipman
1,299 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

How null propagating operator works in C#

Null propagating operator (?) is in C# to make it easier to handle null values in property or method call chain and stop it as soon as first null value is found.

Consider the following example where first child of John Doe is written out to console. Take a good look on this code and think if this is good code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public List<Person> Children { get; set; }
}
public class Program
{
static void Main(string[] args)
{
var customer = new Person { Name = "John Doe" };
Console.Write("First child: ");
if (customer.Children != null)
if (customer.Children.FirstOrDefault() != null)
Console.WriteLine(customer.Children.First().Name);
else
Console.WriteLine("-");
else
Console.WriteLine("-");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The code above is ugly. It's possible to hide it to some property or method of Person class but it doesn't solve the problem as long as the code looks like it is.

Null propagation operator helps us to make this code readable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public List<Person> Children { get; set; }
}
public class Program
{
static void Main(string[] args)
{
var customer = new Person { Name = "John Doe" };
·
Console.Write("First child: ");
Console.WriteLine(customer.Children?.FirstOrDefault()?.Name ?? "-");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

As soon as something before ?. is null the call chain is stopped and null is returned. The line that writes out name of first child first gets name of first child and if it is null then "-" is returned instead.

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content