Null coalescing operator override

c#

Solution

What you're looking for is called Monadic Null Checking. It is currently not available in C# 5, but apparently it will be available in C# 6.0.

From this post:

7. Monadic null checking

Removes the need to check for nulls before accessing properties or methods. Known as the Safe Navigation Operator in Groovy).

Before

if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
}   
return -1;

After

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

in the meantime, just use

`(xstring ?? "xx").ToLower();`

as other answers suggested.

Problem

I know it's non sense to do something like: ``` xstring.ToLower()??"xx" ``` because i called `ToLower()` gets called before checking for null. is there a way around this, keeping the syntax nice and clean? can i override the `??` operator for the string so that it only calls `ToLower()` when `xstring` is not `null`?

Original source

Related problems