Safe Navigation Operator “?.” for D2 ?

Kapps opantm2+spam at gmail.com
Fri Feb 28 04:56:56 PST 2014


On Friday, 28 February 2014 at 11:21:47 UTC, Marc Schütz wrote:
>
> I sometimes come across situations like this:
>
> writeln_or_whatever(person ? person.name : "");
>
> (This is a case of "means something".)
>
> Using `person?.name` is a bit shorter and DRYer. But it would 
> be more useful if I could specify the default value it returns. 
> With an explicit `maybe` this would be possible:
>
> person.maybe("<n/a>").name;


With C#, you can't use 'person' to imply 'person !is null'.
So instead you have
var name = person != null ? person.name : null;
Which is less nice than
var name = person?.name

So this feature is a bit more useful there than here. It also 
ties in well with the ?? operator, for something like:
var name = person?.name ?? "Unknown";


More information about the Digitalmars-d mailing list