Calling constructors with lists of arguments

Arguments may be passed to the class constructor using a number of different approaches.

Using New-Object and the ArgumentList parameter, passing a single argument will use the second constructor in the list on MSDN (and in PowerShell):

PS> New-Object -TypeName System.Text.StringBuilder -ArgumentList 10
Capacity MaxCapacity Length

-------- ----------- ------
10 2147483647 0

Alternatively, the following two approaches may be used:

New-Object System.Text.StringBuilder(10) 
[System.Text.StringBuilder]::new(10) 

PowerShell decides which constructor to use based on the numbers and types of the arguments.

In the previous examples, one argument is passed; there are two possible constructors which accept a single argument. One of these expects a value of type Int32, the other a String.

If a string is passed, a StringBuilder with an initial value for the string will be created. The following example creates a StringBuilder object instance containing the specified string ('Hello world'):

PS> $stringBuilder = New-Object System.Text.StringBuilder('Hello world')
$stringBuilder.ToString()

Hello world

Attempting to pass in a values of other types in may result expected behavior. For example, an argument of $true creates a StringBuilder with a capacity set to 1. The value for $true is treated as an Int32 value:

PS> New-Object System.Text.StringBuilder($true)
Capacity MaxCapacity Length

-------- ----------- ------
1 2147483647 0

If the value for the argument does not match any of the possible constructors, an error will be thrown:

PS> New-Object System.Text.StringBuilder((Get-Date))
New-Object : Cannot convert argument "0", with value: "23/01/2017 15:26:59", for "StringBuilder" to type "System.Int32": "Cannot convert value "23/01/2017 15:26:59" to type
"System.Int32". Error: "Invalid cast from 'DateTime' to 'Int32'.""
At line:1 char:1
+ New-Object System.Text.StringBuilder((Get-Date))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.163.229