0

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?

nPcomp
  • 6,977
  • 1
  • 49
  • 46
  • 2
    Mind that `||=` **assigns** (if I understood it correctly). Whereas `??` has no side-effect itself: it is like a ternary-operator. – Willem Van Onsem Mar 23 '17 at 14:48

2 Answers2

2

Simple answer... yes and no.

The purpose of the ||= operator in Ruby-on-Rails is to assign the left-hand operand to itself if not null, otherwise set it to the the right-hand operand.

In C#, the null coalescing operator ?? makes the same check that ||= does, however it's not used to assign. It serves the same purpose as a != null ? a : b.

Nathangrad
  • 1,376
  • 8
  • 24
1

Based on what I have read here, the x ||= y operator works like:

This is saying, set x to y if x is nil, false, or undefined. Otherwise set it to x.

(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 not null; otherwise it returns the right hand operand.

(formatting added)

Based on that there are two important differences:

  1. The ?? 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
  2. The ?? 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.

Community
  • 1
  • 1
Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485