Future Plans for C# – Null Propagation

Future Plans for C# – Null Propagation

No artigo Future Plans for C# de InfoQ Internacional, temos um ponto que acho bem interessante de ser ressaltado:

Null Propagation

Esse assunto já foi tema de muita discussão no DotNetArchitects em um post sobre Null Object Pattern.

When working with messy data, developers often have to write a series of null checks before reading a property or invoking a method. The ?. syntax would eliminate that by conditionally invoking a method if the preceding value is not null.

var bestValue = points?.FirstOrDefault()?.X;

In this case if points is null, or points.FirstOrDefault() returns a null, then the .X is ignored a null is returned instead. This can then be chained with a ?? to supply an alternate default value.

var bestValue = points?.FirstOrDefault()?.X ?? -1;

This sematic is found in “message passing” languages such as Objective-C and Smalltalk. It is commonly cited as being problematic because what would have been a null reference exception is instead silently ignored.

Vale a lida na matéria original, a matéria é bem curtinha, ótimo para leitura rápida e fala sobre Read-Only Properties, Static Type Using Statements, Primary Constructors, Property and Method Expressions e Function Parameters.