Caffeine-Powered Life

I Want Conditional Assignment in All the Languages

I get that not every language can have every feature. But there are some language features that just seem obvious to me. Conditional assignment is one of those features.

What Is Conditional Assignment?

Not every language has this feature. The super short answer is that it is an assignment that happens conditionally. Specifically, it prevents assignment from happening twice. In these examples, suppose we want to ensure we have defined an array. I’ll use integers, but it really doesn’t matter what you’re putting in the object.

In C#, you would do conditional assignment one of these two ways.

csharp_example.cs
1
2
3
4
5
// Using the ternary operator
array = (array != null) ? array : new int[] { };

// Using the null coalesce operator
array = (array ?? new int[] { });

In JavaScript, you can use the or || operator to accomplish the same thing. This works in JS because the || operator returns a value, not a boolean.

javascript_example.js
1
array = (array || []);

Examples of Conditional Operators

Having conditional assignment takes care of null checks for you. It’s one of those things that makes a language simple on the eyes, and it cuts down on character noise. Here’s what it would look like in CoffeeScript.

coffeescript_example.coffee
1
2
3
4
5
6
7
8
9
10
11
# Using ternary
array = array ? array : []

# Using unless
array = [] unless array

# Using JavaScript, because JS still works in CS
array = (array || [])

# Using conditional assignment!
array ?= []

In Ruby, conditional assignment looks like this.

ruby_example.rb
1
array ||= []

I don’t see any reason we couldn’t add this feature to C#. We have assignment. We have null checks. Create a new operator for the language!

enhanced_csharp_example.cs
1
array ??= new int[] { }

I want this feature in every language. Language designers, go make that happen!