A user on the newsgroup wondered whether the example below highlighted a bug or a feature. They applied multiple type declarations on a single parameter and Windows PowerShell did not complain.
function check {
param([string] [int] $y = 0, $x = 0)
###^^^^^^^^^^^^
$x.GetType().ToString();
$y.GetType().ToString();
$x + $y;
}
That’s no bug, that’s a feature. 🙂
This is an example of chained type casting. There are all sorts of examples where this is useful. Consider the following:
PS> “PowerShell”
PowerShell
PS> [int[]]”PowerShell”
Cannot convert value “PowerShell” to type “System.Int32[]”. Error: “Invalid
cast from ‘System.String’ to ‘System.Int32[]’.”
At line:1 char:8
+ [int[]]” <<<< PowerShell”
PS> [char[]]”PowerShell”
P
o
w
e
r
S
h
e
l
l
PS> [int[]][char[]]”PowerShell”
80
111
119
101
114
83
104
101
108
108
PS> [char[]][int[]][char[]]”PowerShell”
P
o
w
e
r
S
h
e
l
l
PS> [string][char[]][int[]][char[]]”PowerShell”
P o w e r S h e l l
PS>
Enjoy!
Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
PSMDTAG:FAQ: What are cascading type casts?
PSMDTAG:DOTNET: [char[]]
0 comments