Cascading Type Casts

Cascading Type Casts

  • Comments 3

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

Leave a Comment
  • Please add 6 and 2 and type the answer here:
  • Post
  • 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?
  • In my blog entry regarding Cascading Type Casts ( http://blogs.msdn.com/powershell/archive/2006/07/15/Cascading_Type_Casts.aspx&amp;nbsp;)...
  • Since the String class has a constructor taking af Char[], you can use

    PS> New-Object String ( , [char[]]"PowerShell" )

    /JeppeSN

Page 1 of 1 (3 items)