Skip to content
Cameron Purdy edited this page Apr 7, 2020 · 4 revisions

The "Elvis" expression is named after the text-based emoticon for Elvis Presley: ?:p. It takes the form[1]:

a ?: b

The type of the expression a must be of a type whose value could be Null; typically, this means that the type is Nullable. The implicit type of the expression is the bi-implicit type of the non-nullable remainder of the type of expression a and the type of expression b.

If the expression a yields a value other than Null, then the expression yields the result of the expression a. If the expression a yields Null or short-circuits, then the expression yields the result of the expression b. In other words, it is very similar in its behavior to the following, with the primary difference being that the expression a is only evaluated once in the Elvis expression form:

a != Null ? a : b

The expression short-circuits if expression b short-circuits.

Definite assignment rules:

  • The VAS before a is the VAS before the expression.
  • The VAS before b is the join of the VAS after a with the VAS from each short-circuiting point in a.
  • The VAS after the expression is the join of the VAS after a and the VAS after b.
  • If the type of the expression is Boolean, then:
    • The VAST after the expression is the join of the VAST after a and the VAST after b.
    • The VASF after the expression is the join of the VASF after a and the VASF after b.

Note that the Elvis operator groups to the right, which is different from most other binary operators:

    ElvisExpression:
        PrefixExpression
        PrefixExpression ?: ElvisExpression

That means that a ?: b ?: c is treated the same as a ?: (b ?: c).


[1]

C# uses the ?? "null coalescing" operator for the same purpose, which makes Baby Elvis cry. See https://en.wikipedia.org/wiki/Null_coalescing_operator