Powershell: Suggestion: implement ternary conditionals

Created on 2 Mar 2017  ·  52Comments  ·  Source: PowerShell/PowerShell

C-style ternary conditionals would be a handy addition to the language.

For instance, instead of writing:

if ((get-date).tostring("ss") % 2) { 'odd'  } else  { 'even' }

one could write:

(get-date).tostring("ss") % 2   ?   'odd'   :    'even'

It would also relieve a long-standing disappointment:

At Microsoft, “to ship is to choose”. One of the things we were very disappointed in not being able to ship in V1.0 is a ternary operator.

From a PowerShell Team blog post dated 29 December 2006.


Related: implement null-coalescence and null-soaking and null-conditional assignments

Committee-Reviewed Issue-Enhancement WG-Language

Most helpful comment

@RichardSiddaway: If we look on Stack Overflow at PowerShell-tagged questions _asked since 2014_, we get (as of this writing):

$PSItem was introduced in v3 in September 2012, so to be safe I chose 2014 as the start date for the query.

While this is not an exact metric, - the site doesn't allow you to search for $_ or _, unfortunately, and I'm sure there are questions that contain _neither_ $_ nor $PSItem, and pre-v3 questions are still being asked - I still think it's safe to conclude that $_ is used far more frequently than $PSItem.

However, the larger point is that there's no need to _choose_:

Just as $PSItem and $_ happily coexist, so do ForEach-Object and %, Where-Object and ?, ...:

$a ? $b : $c can coexist with if ($a) { $b } else { $c } / $(if ($a) { $b } else { $c })

As for recapping the _positive_ reasons to introduce $a ? $b : $c

  • more concise, less visually cluttered, using syntax familiar to most programmers.

  • more efficient, because there is no need for $(...), which if statements need in order to allow their use as part of a larger expression (which is noisier, less efficient, and can have unintended side effects)

As for the obscurity concern:

Someone writing _expressions_ (as opposed to merely _invoking commands_ with (simple) arguments) can be assumed to have some developer experience, and my (anecdotal) sense is that most developers at least _recognize_ $a ? $b : $c as a condensed if statement, whether or not they actively use it.

Even if they don't, however, it's easily explained, and aside from the use of non-obvious _symbols_, the conceptual complexity is the same as that of an if ($a) { $b } else { $c }, and even less than
$(if ($a) { $b } else { $c })

Assuming that it catches on once introduced - certainly, this discussion shows that there's demand for it - encountering it frequently will make it a familiar and easily recognizable idiom (that is more concise, easier to type and, at least to me and a few others here, more readable) - just like most people seem to prefer $_ over $PSItem.

All 52 comments

Note that with the change to allow assignments from statements, the need for a ternary operator is reduced. You can simply do
$var = if ($x) { $x } else { $y }
It's not as concise as the ternary operator but is arguably more readable.

Yes, though you still have to use $(...) _in addition_ if the conditional is part of a larger expression:

'The current sec. is ' + $(if ((get-date).tostring("ss") % 2) { 'odd'  } else  { 'even' })

vs.

powershell 'The current sec. is ' + ((get-date).tostring("ss") % 2 ? 'odd' : 'even')

I know that readability is in the eye of the ... uh ... reader, but I personally find the latter visually easier to parse, and having to type less is always a bonus.

With such a frequently used feature, I think remembering the more abstract ternary syntax wouldn't be a problem (and, of course, people can continue to use if, if they prefer).

@mklement0 I have to agree later has less cognitive load.

This is definitely on my top list to.
@BrucePay, are there any reasons that this would be a bad idea? Or is it just about 'to ship is to choose' ?

In the past, this feature request was turned down as being harder for less experienced scripters to understand, and that the expression form of the if statement was a clearer, though more verbose alternative.

My personal perspective: if the language was just for me, I'd probably have added it a long time ago. But ... I find many developers don't use it, which actually suggests there is some truth to the hypothesis that less experienced folks will have trouble with the ternary operator.

@lzybkr:

It's worth distinguishing between _active use_ of a feature vs. the ability to _recognize_ and understand it.

Clearly, everyone gets to choose whether to use such a feature, but are you saying that "have trouble with" means that less experienced folks won't _understand_ it when they see it in the code of others?

@mklement0 - we introduced $psitem as an alias for $_ because of sufficient feedback that $_ was cryptic and confusing, so I do believe the ternary operator would be difficult for some less experienced people to understand.

On the other hand, there are many elements in PowerShell that are confusing to beginners, or even to quite experienced developers.

As with any other language, it takes some effort to learn the syntax and meaning of language constructs.
I don't know if I think the ternary operator is especially difficult to grasp.

Do you have data suggesting that it is?

I believe the only data is anecdotal, but the criticism applies to any cryptic language - bash, perl, etc.

And to be clear, I was providing the historical context. Maybe PowerShell is ubiquitous enough now that more cryptic syntax won't affect adoption.

Also keep in mind - some terse languages still use if/then as the ternary operator, e.g. F#.

That said, maybe it's possible to use fewer characters and not be too cryptic:

if ($x) { $y } else { $z }
$x -then $y -else $z
$x ? $y : $z

-then/-else fits well with PowerShell syntax - but, an operator (or operators if it's too confusing to think of as a single operator), you gain the benefit of not needing parens and braces.

Then again, this is asking for trouble similar to foreach vs. foreach-object. but maybe it's not as bad, I don't know.

@lzybkr:

Cryptic in homeopathic doses is healthy:

PowerShell is commendably not cryptic overall, but in some cases offers cryptic syntax as a concise _alternative_ (you still can be verbose if desired) for _frequently used_ constructs, notably ? for Where-Object and % for ForEach-Object.

Providing $x ? $y : $z as a concise alternative to if ($x) then { $y } else { $z } to me is in the same spirit.

The cryptic aspect is ameliorated by ? being reminiscent of a _question_ and therefore suggesting a conditional (albeit one _preceding_ the ? in this case), and - more importantly - being _a potentially familiar construct from several other languages_, with the same fundamental semantics.

You don't get the same benefit with $x -then $y -else $z: it is not familiar.

Also, while many PS operators do have symbolic names, many do not: * / + % ...
These are inherently cryptic too, we just don't perceive them that way anymore, because they are so familiar and ubiquitous.

My sense is that $x ? $y : $z too is already familiar to many, and will become even more so once introduced into the language, given the frequent need for concise conditionals.

Note that you'll be pretty limited in what you can specify with this operator. In particular you won't be able to use commands unless you wrap them in parenthesis:

(test-path foo.txt) ? (get-content foo.txt) : (get-content bar.txt)

compared with

if (test-path foo.txt) {get-content foo.txt} else {get-content bar.txt}

or

get-content ((test-path foo.txt) ? "foo.txt" : "bar.txt")

vs

get-content $(if (test-path foo.txt) {"foo.txt"} else {"bar.txt"})

To my mind, there is little advantage in terms of brevity and a distinct disadvantage in readability. The ternary operator is far less interesting when you have an expression oriented language. When I started on the language 16 years ago, adding the ternary operator seemed obvious coming from a C background. Now I'm glad we never added it. It just feels like clutter.

In particular you won't be able to use commands unless you wrap them in parentheses:

That applies to _any_ PowerShell operator.

Not all PowerShell statements involve commands, and when they do, users already know that (...) is the price of admission for commands (in most cases).

In your own example, to me ((test-path foo.txt) ? "foo.txt" : "bar.txt") beats $(if (test-path foo.txt) {"foo.txt"} else {"bar.txt"}), both for the obscurity of needing $(...) and the noise introduced by the curly braces.

Maybe it's just me but I find this:

get-content ((test-path foo.txt) ? "foo.txt" : "bar.txt")

way easier to visually scan/parse than this:

get-content $(if (test-path foo.txt) {"foo.txt"} else {"bar.txt"})

My only complaint about this issue is that if you're going to do ternary ?: then you should also do null-coalescing ??:

$logDir = $env:LogDir ?? "$PSScriptRoot\Log"

I've seen a number of Invoke-Ternary and Invoke-NullCoalescing implementations in the wild (e.g. https://github.com/dahlbyk/posh-git/blob/master/src/Utils.ps1#L12). That kind of indicates there is a general desire for such a feature baked into the language.

@rkeithhill: I agree; re null-coalescing: there is an issue already, which also covers null-soaking: #3240

So the argument of less experienced coders wouldn't be able to easily use a null-coalescing or ternary code statement I think is a little short-sighted. There's no requirement to use these "advanced" features and if a programmer can't read the code because they lack the experience, then personally that's my cue that I need to learn something new really quick.
When I first saw a ternary in C# I was like WTF is this fresh hell MS has introduced, until I took a few minutes to read up on this, which then I was hooked.

Practical example in POSH, I have this line:
$mc_object = ($Message.fields | where Name -Match appname).Content
which is fine and dandy except when the $Message object does not have a filed property that has a name of "app name", and since I don't control the JSON formatted data this comes from, I have to determine what to do.

So with a null-coalesce operations all I have to do is add ?? "" at the end to make sure that the $mc_object always was a valid string, even if the original setter was null. Otherwise, I would have to do some different techniques to accomplish what 4 keystrokes can do, such as
$mc_object = if(-not ($Message.fields | where Name -Match appname).Content)){""}else{($Message.fields | where Name -Match appname).Content}
That to me is very unreadable, but then I can clean this up a little bit by doing something like this, which is what I am doing.
$mc_object = ($Message.fields | where Name -Match appname).Content if(-not $mc_object){$mc_object = ""}

While not terrible, it's a heck of a lot more than 4 keys being pressed to null-coelasce.

Anyhow, I definitely vote for ternary and null-coelasce in Powershell, it adds some very advanced features and just makes Powershell more compelling to use in the "core" form on any system.

@lzybkr I have yet to see anyone actually adopt $PSItem. I work on a decently large team of people who write scripts and they still all use $_, even the less-experienced PowerShell users.

@tibmeister or....

if (-not ($mc_object = $Message.fields.where{$_.Name -match 'appname'}.Content)) {
    $mc_object = ''
}

Assignments as expressions will passthru, but are incredibly unreadable.

I regularly use $psitem

Over a number of years of judging Scripting Games $psitem was used a lot in the answers

@RichardSiddaway: If we look on Stack Overflow at PowerShell-tagged questions _asked since 2014_, we get (as of this writing):

$PSItem was introduced in v3 in September 2012, so to be safe I chose 2014 as the start date for the query.

While this is not an exact metric, - the site doesn't allow you to search for $_ or _, unfortunately, and I'm sure there are questions that contain _neither_ $_ nor $PSItem, and pre-v3 questions are still being asked - I still think it's safe to conclude that $_ is used far more frequently than $PSItem.

However, the larger point is that there's no need to _choose_:

Just as $PSItem and $_ happily coexist, so do ForEach-Object and %, Where-Object and ?, ...:

$a ? $b : $c can coexist with if ($a) { $b } else { $c } / $(if ($a) { $b } else { $c })

As for recapping the _positive_ reasons to introduce $a ? $b : $c

  • more concise, less visually cluttered, using syntax familiar to most programmers.

  • more efficient, because there is no need for $(...), which if statements need in order to allow their use as part of a larger expression (which is noisier, less efficient, and can have unintended side effects)

As for the obscurity concern:

Someone writing _expressions_ (as opposed to merely _invoking commands_ with (simple) arguments) can be assumed to have some developer experience, and my (anecdotal) sense is that most developers at least _recognize_ $a ? $b : $c as a condensed if statement, whether or not they actively use it.

Even if they don't, however, it's easily explained, and aside from the use of non-obvious _symbols_, the conceptual complexity is the same as that of an if ($a) { $b } else { $c }, and even less than
$(if ($a) { $b } else { $c })

Assuming that it catches on once introduced - certainly, this discussion shows that there's demand for it - encountering it frequently will make it a familiar and easily recognizable idiom (that is more concise, easier to type and, at least to me and a few others here, more readable) - just like most people seem to prefer $_ over $PSItem.

mklement0, you have a very awesome example and I think demonstrates the point clearly, thank you.

Rereading and revisiting this and looking at some of the questions, I find myself leaning more towards the slightly more verbose syntaxes suggested:

$value = $a -eq $b -then $trueVal -else $falseval

or, for a more semantically readable syntax:

$value = $trueVal -if $a -eq $b -else $falseVal

@vexx32 While I don't mind your first example, I find the condition in the middle of an expression extremely heavy.

Yeah, I think I tend to agree, but it does read slightly more... smoothly. But I'd still tend to go to the first.

Given that PowerShell is intended to be an "on ramp" language to C#, I think using ? : is the way to go. Even JavaScript uses this syntax and it is one of the most popular languages these days. :-)

Agreed, @rkeithhill, both for the familiarity of the construct from several other languages _and_ the desire to also have null-coalescing, null-soaking, and null-conditional assignments, which in C# are based on ? too.

The latter two - e.g. $foo?.bar and $var ?= 'default val' - aren't really possible without a symbol-based representation, and even for null-coalescing $a ?? 'value-if-null' seems preferable to something like $a -elseifnull 'value-if-null'.

Remember that ?, as a frequently used alias for Where-Object, is already firmly entrenched as representing a _conditional_, so transferring that knowledge to variations of its use seems logical.

Is PowerShell really an on-ramp to C# ? i know that was a stated intent 10-12 years ago but is it really happening? My suspicion is that for the majority of PowerShell users C# isn't somewhere they want to go.

if ternary conditionals are going to happen I'd prefer to see something like
$value = $trueVal -if $a -eq $b -else $falseVal

as mentioned by @vexx32

It makes more sense for the average PowerShell user.

@mklement0 My comments about $psitem were based on my personal experience. If you've had a different experience it doesn't invalidate my experience

i know that was a stated intent 10-12 years ago

Yup, at the early MVP summits among other places by Jeffrey. I haven't heard any different since then.

Also, nearly all of the conditional/loop constructs take from C# (and the C lineage), if {}, while {}, do {} while, switch {},for {},foreach {},try {} catch {} finally {}`. It makes sense to me that this conditional construct would too.

Those are language keywords, though, @rkeithhill. Operators are entirely different.

I think you'll find that the vast majority of operators used in PowerShell to be quite different from their C# equivalents. The PS team have very clearly opted for a more descriptive syntax for the majority of the operators.

I would consider that ternary behaviour should also take after the more verbose syntax options available. PowerShell may have been conceived as an 'on-ramp' to C#, but that does not mean it should inherit its more symbolic syntaxes. Indeed, there are many places where that has been painstakingly avoided.

Consider, if you would, that your arguments for the symbolic syntax are rooted in how other common programming languages represent this concept. PowerShell has not been one to go that route in the post, instead preferring to work with as descriptive a syntax as can be made sensible. Merely because those of use who already have experience in C# are familiar with such syntax is assuredly not a reason to use it.

If PowerShell is an 'on-ramp' language to C# or any other language (which, I feel, it does fairly well at this far) then we need to consider the lowest common denominator here and think about what the most inexperienced persons would find sensible and intuitive.

I'm not saying my proffered solutions are it, but I think they're possibly headed in a more sensible direction from this perspective.

@vexx32
How about these operators?

.
=
[]
,
+ - * / %
++ --
+=  -=  *=  /= %=

Generally, I agree that following C#'s lead is not always appropriate, and that preserving the spirit of PowerShell should take precedence.

Conversely, I'd advise against deviating from C# in cases where the same syntax does seem like a plausible fit, and to me the proposal at hand - along with #3240 - is an instance of that.

If we leave other languages aside:

  • The current semantics of ? plausibly extend to the proposed operators.

  • If you see value in the _related_ operators being proposed - null-soaking (?.), null-coalescing (??) and null-conditional assignment (?=) - then opting for a verbose ternary form such as -then / -else is not an option, if you want all these related operators to reflect a commonality (which they obviously conceptually have).

The more exotic a feature is, the more verbosity is important.

The more frequently used a feature is, the more concision is important. And the abstractness of a symbol-based representation ceases to be a problem through sheer repeated exposure to the syntax - just as with *, for instance.

All of the operators being discussed to me fall into the latter category.


@RichardSiddaway:

My comments about $psitem were based on my personal experience. If you've had a different experience it doesn't invalidate my experience

Yes, your comments were based on _personal_ experience.
Mine were based on _analyzing data_ from popular Q & A site Stack Overflow, to infer _general_ usage patterns (within the constraints stated) - which is unrelated to my personal experience.

The only reason you could perceive my comments as invalidating yours if you believe your personal observations to reflect a "transpersonal" truth - a claim you didn't make as such in your comments. Did you mean to make it? If so, we need to discuss _that_.

Almost all those operators are mathematical operators with relatively clearly-understood meaning, @mklement0 😄

A ternary operator is a conditional operator, and _all_ of PS's Boolean/conditional operators are of the more verbose form: -and, -or, -eq, -ne, -contains, etc.

I agree that this shorthand may make sense due to the need for the surrounding features and related operators, however. But I do think that the "standard" ternary syntax is not particularly intuitive to those of us who have not been repeatedly exposed to it already.

operators are mathematical operators

Among those listed, only + - * / % have (purely) mathematical meaning, but the clearly-understood aspect applies to the others too (with the exception of =, given that it is often confused with equality testing).

The better construct to compare <condition> ? <if-true> : <else> to is the if _statement_, not other operators. While if is definitely more verbose, it is precisely that aspect that the ternary operation is meant to address (in addition to being a true, composable expression, unlike if).

There is a spectrum of concision, for sure, but, as you say, to accommodate all related operators being proposed in a consistent fashion, a symbol-based syntax makes sense.

to those of us who have not been repeatedly exposed to it already.

Well, that will hopefully change soon. 😁
Point taken, but (a) the syntax is easily explained and has the same conceptual complexity as an if statement, and (b) repeated exposure should help with memory retention.

@mklement0 How do you suggest addressing ? being a valid name character? Breaking change? I consider people on powershell core to be well-versed in powershell as it is and that additional syntax (that has existed in other languages for nearing 50 years) will not be a hindrance. They can always use if/else if they want more verbosity.

? is only a valid alias in command mode; in all variants of expression mode it's simply an invalid character at present. There is no collision.

If you attempt to enter this code, it will simply error out:

$Value = $true
$Value ? "Hello!" : "Goodbye!"

Result:

At line:1 char:8
+ $Value ? "Hello!" : "Goodbye!"
+        ~
Unexpected token '?' in expression or statement.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken

@vexx32

$what? # <- example of a valid variable name

In his null-soaking example: $var?.maybenull() doesn't care that there's a question mark there and if someone is trying to be overly condense, their ternary will break.

Sorry, that was mainly being discussed in the other issue on that so I didn't think you were referring to that.

Whether or not we can preclude that from being a valid variable name character is up to the PS team, but I am inclined to be of the opinion that preventing it being considered a variable name character by default would not break much. I don't think I've ever seen anyone actually use ? as part of a variable name.

@vexx32 Yeah, I should bring that up over there. This could have additional impacts if not careful with scoping as well (although this is already seen in string expansions so people should be somewhat familiar with it):

$var = $test?$thing1:$thing2

but I may be splitting hairs too much on edge-cases for those of us who live in the shell.

Corrected:

$var = ${test}?${thing1}:$thing2

@mklement0 - I don't necessarily agree with:

The better construct to compare ? : to is the if statement, not other operators. While if is definitely more verbose, it is precisely that aspect that the ternary operation is meant to address (in addition to being a true, composable expression, unlike if).

Specifically, the ternary operator exists because C/C# are statement oriented languages but needed conditional expressions.

In expression oriented languages (e.g. F# or Rust), there is no terse syntax as it's considered unnecessary. I think this old discussion on Rust removing the ternary operator is interesting.

One thing I really like in Rust is the use of the ? operator for error handling. I don't have a concrete proposal to use ? in PowerShell, but it feels like ? could be better used for error handling than for a conditional expression.

@TheIncorrigible1, @vexx32: Yes, null-soaking would technically be a breaking change, but hopefully of type bucket 3 (indeed, let's continue the discussion there); for the ternary operation, the suggested use of {...} / whitespace before ? for disambiguation seems to solve that problem.

@lzybkr:

Specifically, the ternary operator exists because C/C# are statement oriented languages but needed conditional expressions.

Well, in PowerShell flow-control statements such as if are _half_-expressions; in _simple_ expressions, the proposed ternary operation would be equivalent; in _nested_ ones, it wouldn't:

$foo = $True  ?     1   :      0    # proposed ternary
$foo = if ($True) { 1 } else { 0 }  # equivalent `if` statement
$foo = 1 + ($True  ?     1   :      0)   # nesting OK; note that + would have higher precedence
$foo = 1 + if ($True) { 1 } else { 0 }  # !! doesn't work
$foo = 1 + (if ($True) { 1 } else { 0 })  # !! doesn't work, even with parentheses
$foo = 1 + $(if ($True) { 1 } else { 0 })  # only $(...) (and situationally @(...)) work

The need for $() / @() is more than just a syntax inconvenience: it has behavioral and performance implications.

That said, I _wish_ that statements such as if and foreach were bona fide expressions (two more examples of things currently failing: foreach ($i in 1..5) { $i } | Write-Output or foreach ($i in 1..5) { $i } > out.txt).
I don't know enough to judge whether they _cannot be_, however and/or if there's a backward-compatibility concern.
See also: #6817


If if were to become a full expression in PowerShell, then you could make the argument that led to the removal of the ternary conditional from Rust: it is then no longer _necessary_.

However, my motivation for this proposal was never _necessity_ - it's about concision, convenience, and readability (visual clutter).


I don't have a concrete proposal to use ? in PowerShell, but it feels like ? could be better used for error handling than for a conditional expression.

I think that introducing ? with fundamentally different semantics than in C# would be a source of everlasting confusion.

Separately, improvements in PowerShell's error handling are well worth discussing.

If we are looking for a concise but unintuitive alternative to If/Then/Else, we already have one.

( 'False', 'True' )[( Test-Condition )]

And it works in expressions.

"This statement is " + ( 'False', 'True' )[( Test-Condition )]

@TimCurwick: That's concise (and more obscure), but not equivalent: the proposed ternary conditional would be _short-circuiting_ (just like an if statement), whereas your syntax invariably evaluates _both_ alternatives.

That said, your syntax is certainly the next best thing available currently, assuming one is aware of the stated limitation.

Regarding the discussion of how to display ternary choices in PowerShell, has anyone considered an option in the same format as used by -replace / .replace()?

$a -eq $b -ternary $a,$c
$true -ternary 1,0

or

($a -eq $b).ternary($a,$c)
($true).ternary(1,0)

This would make it a clear that the operator is performing a ternary action by literally calling it ternary. It's verbose, but still short to write, and it makes use of the existing common behaviour of -operator $first,$second, so it should feel familiar for powershell users across all ranges of experience

🤔 it might work, but it would be more awkward than any of the proposed alternatives. -replace works that way because it just accepts an actual array of arguments. .Replace() is not managed by the PS team -- it's a method on the .NET System.String class.

If we were to try to use either of those syntaxes it'd mean either an ETS method (which is OK, but tends to add a bit of performance overhead to creation of objects it needs to be attached to) or, with the operator version you propose, we wouldn't be able to easily have an array as an argument.

Without special-casing such an operator in the parser, we wouldn't be able to short-circuit. Ternary syntaxes in other languages generally exist because you _don't want_ to actually evaluate both options; the compute time is quicker if only the correct branch needs to be evaluated, rather than having to full evaluate both options (which might come with some significant side effects).

And since that would already require special-casing, it would be more effective to introduce new syntax for it, to minimise confusion (it would be a bit misleading to have something that looks like an array but can't be used like one; it wouldn't support creating the "array" ahead of time and passing that as a variable, for example). The fact that method arguments already conflict a bit with array syntax is often already misleading. I don't think I'd want to add a _third_ variant behaviour for commas to the mix.

@PowerShell/powershell-committee discussed this at length, we don't all agree, but a majority agree that there is value in having this operator and to align with C# syntax keeping ?: as expectation is that most usage will be from C# developers. This feature will be Experimental pending real usage feedback.

@SteveL-MSFT So that means the feature is moving forward for 7.0? Will it break compatibility on variables being able to use ? in their symbol?

@TheIncorrigible1 yes, this feature is moving forward in PS7. It should not break compatibility with use of ? alias. There is a concern about the visual acuity of ? when glancing at a script trying to differentiate Where-Object and ternary, but we'll see what the user feedback is on this. In general, we don't expect most users to use this operator but that should not prevent it from moving forward.

@SteveL-MSFT I mean variables with a name of $isValid? or similar. These are valid tokens in the current iteration of PS.

@TheIncorrigible1:

Requiring whitespace between the first operand and the ? solves that problem, as previously suggested, and to me it is a perfectly reasonable solution:

  • The : _also_ requires whitespace around it, because something like $true ? $number:42 wouldn't work, given that $number:42 would _as a whole_ be interpreted as a single variable reference.

  • While C# _does_ allow true?number:42, I don't think we need to - or, indeed, can - worry about compatibility at that level. I personally value concision, but not at the expense of readability; even if I _could_ write $true?$number:42, I wouldn't.

(Backward compatibility will indeed be a problem when (hint, hint) we implement null-conditional access. PowerShell's permissiveness with respect to identifier names is generally problematic, as @KirkMunro has recently argued, but that ship has sailed)

Yeah, I think leaving the whitespace requirement is sensible. It's terse enough as it is, after all. 😁

The prototype tried pretty hard to parse numbers with ? and : in them differently in the context of ternary operator (where we know we are expecting an expression). So you can write things like ${isWindows}?12:47.
Numbers like 123? or 1:23 are tokenized as a generic token today, which is not useful at all in the case where we know we are expecting an expression.

For variables, no change at all to how ? or : can be used for the variable name, since variable is an expression.

Good point, @daxian-dbw; I forgot that {...} can be used to resolve any variable-name boundary ambiguity, so I guess code golfers could use something like ${isWindows}?${number}:47

Can we close this now?

Close via #10367

Was this page helpful?
0 / 5 - 0 ratings