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.
1 2 3 4 5 | |
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.
1
| |
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.
1 2 3 4 5 6 7 8 9 10 11 | |
In Ruby, conditional assignment looks like this.
1
| |
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!
1
| |
I want this feature in every language. Language designers, go make that happen!