I was using the ||=
operator in Ruby on Rails and I saw that C# have something similar.
Is ||=
in Ruby on Rails equals to ??
in C# ?
What is the difference if there is one?
Based on what I have read here, the x ||= y
operator works like:
This is saying, set
x
toy
ifx
isnil
,false
, orundefined
. Otherwise set it tox
.
(modified, generalized, formatting added)
The null-coalescing operator ??
on the other hand is defined like:
The
??
operator is called the null-coalescing operator. It returns the left-hand operand if the operand is notnull
; otherwise it returns the right hand operand.
(formatting added)
Based on that there are two important differences:
??
does not assign, it is like a ternary operator. The outcome can be assigned, but other things can be done with it: assign it to another variable for instance, or call a method on it; and??
only checks for null
(and for instance not for false
), whereas ||=
works with nil
, false
and undefined
.But I agree they have some "similar purpose" although ||
in Ruby is probably more similar with ??
, but it still violates (2).
Also mind that the left part of the null-coalescing operator does not have to be a variable: on could write:
Foo() ?? 0
So here we call a Foo
method.