Disabling the Null Coalescence Operator

I know that it doesn’t make sense to do something like:

xstring.ToLower()??"xx" 

because I called ToLower() , it is called before checking null. is there any way around this while keeping the syntax nice and clean?

can I override the operator ?? for a string so that it only ToLower() when xstring not null ?

+3
c #
source share
8 answers

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

From this post :

7. Monadic null check

Removes the need to check for zeros before accessing properties or methods. Known as the secure 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.

+8
source share

No, you cannot overload this statement. Just put .ToLower beyond coalescence:

 (xstring ?? "xx").ToLower(); 
+8
source share

No, but there are rumors that the operator ?. added to the next version of C # for this purpose. See No. 7 at http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated

+4
source share

If you want to avoid ToLower () - the literal value "xx", you are stuck with the :: ternary operator.

 xstring != null ? xstring.ToLower() : "xx" 

Or you could write an extension method, but it looks very strange to me.

 public static string ToLowerOrDefault(this string input, this string defaultValue) { return (input != null ? input.ToLower() : defaultValue); } 

which you could use as follows:

 xstring.ToLowerOrDefault("xx") 
+3
source share

Apply the ToLower() method after checking for null :

 (xstring ?? "xx").ToLower(); 
+3
source share

according to ECMA-334 you cannot override ?? Operator

ECMA-334 standard

+2
source share

The only solution I've seen will make:

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

However, I think it would be much better if you did something.

 xstring != null ? xstring.ToLower() : "xx" 
+2
source share

You can use:

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

The syntax is simple and the goal is clear. On the other hand, you will run ToLower on "xx" and you have added some parentheses.

+2
source share

All Articles