Search code examples
c#ruby-on-railsoperatorsnull-coalescing-operator

equality and null check (Ruby-on-Rails and c#)


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?


Solution

  • 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.