user1492051
user1492051

Reputation: 906

Null coalescing operator override

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?

Upvotes: 3

Views: 751

Answers (8)

Tim S.
Tim S.

Reputation: 56536

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.

Upvotes: 2

gleng
gleng

Reputation: 6304

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"

Upvotes: 2

Fede
Fede

Reputation: 44038

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.

Upvotes: 8

Kaf
Kaf

Reputation: 33829

Apply ToLower() method after checking for null:

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

Upvotes: 3

D Stanley
D Stanley

Reputation: 152566

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

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

Upvotes: 8

santosh singh
santosh singh

Reputation: 28652

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

Standard ECMA-334

Upvotes: 2

Robert Levy
Robert Levy

Reputation: 29073

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

Upvotes: 4

Michael Gunter
Michael Gunter

Reputation: 12811

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")

Upvotes: 3

Related Questions