Null Coalescing ?? Operator

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

I do like C# 2's new ?? operator, which enables us to code something like:

// Ensure someString is not null
someString = someString ?? "";

But wouldn't it make a lot of sense to take this a step further and allow a
shorthand-assignment equivalent (much like +=, -= and so on)? I.e instead of
what we have above, we could just say:

someString ??= "";

Now that would be nice...

Rich
 
Rich,

But what would it do? It would only set the variable if the variable is
null?
 
Nicholas Paldino said:
But what would it do? It would only set the variable if the variable is
null?

Presumably so. You'd do something like:

s ??= someValue1;
// More code
s ??= someValue2;
// More code
s ??= someValue3;

and the final value of s would be the first non-null value used.

I'm not sure I like it quite enough to think it's worth adding as an
operator, but I'm sure there are some situations in which is would be
useful.
 
If there is a use, I can't see it. I mean, are we really THAT lazy
where we need a whole new operator (and reams of code to support it in the
compiler) for one single word?
 
Nicholas Paldino said:
If there is a use, I can't see it. I mean, are we really THAT lazy
where we need a whole new operator (and reams of code to support it in the
compiler) for one single word?

Couldn't the same be applied to +=, -= etc too? It's only a single word
each time...

(Actually, there's a difference between x += y and x = x + y, I know,
but arguably that subtlety is confusing anyway.)

There are lots of bits of syntactic sugar which aren't really
necessary. I suspect this one is a step too far, but I'll keep an eye
out for where I *would* use it...
 
string foo = null;
return foo ?? "foo was null";

equals to

string foo = null;
return foo == null ? "foo was null" : foo;
 
Couldn't the same be applied to +=, -= etc too? It's only a single word
each time...

(Actually, there's a difference between x += y and x = x + y, I know,
but arguably that subtlety is confusing anyway.)
<snip Jon>

Yes, there's a difference between x += y and x = x + y, but what about
the ever present x++ (3chars) instead of x += 1 (4 chars). And the
second one is more "useful" since it could be x += any number.

Scott
 
Scott said:
<snip Jon>

Yes, there's a difference between x += y and x = x + y, but what about
the ever present x++ (3chars) instead of x += 1 (4 chars). And the
second one is more "useful" since it could be x += any number.

Indeed. So, the question is - where does the line get drawn? I think
it's probably too early to say how often the null coalescing operator
is going to prove useful in a situation where ??= would make sense.
We'll see over the next couple of years - although of course, that
depends on people knowing about it. It's one of the least advertised
new features of C# 2.0, IMO.

Jon
 
Back
Top