Back
Close

Null propagating operator in C#

gpeipman
1,886 views

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.

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.

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

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants