Welcome to MSDN Blogs Sign in | Join | Help

Cascading Type Casts

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[]]

Published Saturday, July 15, 2006 6:29 PM by PowerShellTeam
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Cascading Type Casts

I actually could not understand this last example
PS> [string][char[]][int[]][char[]]"PowerShell"
P o w e r S h e l l

For few times, i have been thinking about casting "[char[]]" to "[string]" to undo split operations(string.Split(...)) but it would generate a string with spaces in-between non-space characters.

Would there be an easier way to put "[char[]]" into a string with no spaces in it?
Saturday, July 15, 2006 2:01 PM by dontBotherMeWithSpam

# PSMDTAG:FAQ: What is $OFS

Saturday, July 15, 2006 6:14 PM by Windows PowerShell

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker