Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Everything you ever wanted to know about the switch statement" – Missing example for switching on types #10911

Closed
SetTrend opened this issue Feb 28, 2024 · 2 comments · Fixed by #10913
Assignees
Labels
area-about Area - About_ topics

Comments

@SetTrend
Copy link
Contributor

Type of issue

Missing information

Feedback

It seems hard to create a switch on types.

The following doesn't work:

$var = @{A = $true; B = 'abc'}

foreach ($key in $var.Keys)
{
  switch ($var[$key].GetType())
  {
    [bool] { if ($var[$key]) { $key } }
    [string] { "$key: $($var[$key])" }
  }
}

May I suggest to add information for this case to the below mentioned documentation page?

Page URL

https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-switch?view=powershell-7.4

Content source URL

https://github.com/MicrosoftDocs/PowerShell-Docs/blob/main/reference/docs-conceptual/learn/deep-dives/everything-about-switch.md

Author

@sdwheeler

Document Id

9c03bc13-a80c-0a4c-0537-81235d4a849c

@SetTrend SetTrend added the needs-triage Waiting - Needs triage label Feb 28, 2024
@sdwheeler
Copy link
Contributor

The type is being parsed as a typecast on the scriptblock. Enclose the matching condition in a script block to avoid the typecast.

switch ($var[$key].GetType())
{
    {$_ -eq [bool]} { if ($var[$key]) { $key } }
    {$_ -eq [string]} { "$key`: $($var[$key])" }
}

@sdwheeler sdwheeler self-assigned this Feb 28, 2024
@sdwheeler sdwheeler added area-about Area - About_ topics and removed needs-triage Waiting - Needs triage labels Feb 28, 2024
@SetTrend
Copy link
Contributor Author

SetTrend commented Feb 28, 2024

Thanks for clarifying, @sdwheeler!

Coincidentally, I just found another GitHub issue, proposing an improvement to the PowerShell language: PowerShell/PowerShell#17456

It claims that it's sufficient to surround the type declaration with parentheses:

switch ($var[$key].GetType())
{
  {[bool]} { if ($var[$key]) { $key } }
  {[string]} { "$key`: $($var[$key])" }
}

I just tested it, and it works.

Perhaps the documentation may give some kind of rule or explanation on when and why parentheses are required in a switch statement condition.

It looks like omitting the parentheses is more or less some kind of special case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-about Area - About_ topics
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants