3

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?

user1492051
  • 886
  • 8
  • 22
  • possible duplicate of [Possible to override null-coalescing operator?](http://stackoverflow.com/questions/349062/possible-to-override-null-coalescing-operator) – Lukazoid Jan 10 '14 at 18:22

8 Answers8

8

No you cannot overload that operator. Just put .ToLower outside of the coalesce:

(xstring ?? "xx").ToLower();
D Stanley
  • 149,601
  • 11
  • 178
  • 240
8

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.

Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
4

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

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
3

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

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

Or you could write an extension method, but this looks very odd to me.

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

which you could then use like this:

xstring.ToLowerOrDefault("xx")
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
3

Apply ToLower() method after checking for null:

(xstring ?? "xx").ToLower();
Kaf
  • 33,101
  • 7
  • 58
  • 78
2

according to ECMA-334 you can not override ?? operator

Standard ECMA-334

santosh singh
  • 27,666
  • 26
  • 83
  • 129
2

The only solution I would see is doing:

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

However, I think it would look much nicer if you did something

xstring != null ? xstring.ToLower() : "xx"
gleng
  • 6,185
  • 4
  • 21
  • 35
2

You could use:

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

The syntax is simple and the intent is clear. On the downside, you'll be running ToLower on "xx" and you added some parentheses.

Tim S.
  • 55,448
  • 7
  • 96
  • 122