Skip to content

Commit 5d7dc2e

Browse files
committed
Merge branch 'sdw-w351599-i10688' of https://github.com/sdwheeler/PowerShell-Docs into sdw-w351599-i10688
2 parents 06ae193 + dde9f60 commit 5d7dc2e

File tree

1 file changed

+80
-79
lines changed

1 file changed

+80
-79
lines changed

reference/7.5/Microsoft.PowerShell.Core/About/about_Type_Conversion.md

Lines changed: 80 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@ must understand how it works to avoid unexpected results.
2121
By default, PowerShell _variables_ aren't _type-constrained_. You can create a
2222
variable containing an instance of one type and later assign values of any
2323
other type. Also, PowerShell automatically converts values to other types, both
24-
explicitly and implicitly. While implicit type conversion is usually helpful,
25-
there are pitfalls, especially for users more familiar with languages have
26-
stricter type handling.
24+
explicitly and implicitly. While implicit type conversion can be helpful, there
25+
are pitfalls, especially for users more familiar with languages have stricter
26+
type handling.
2727

28-
## Type-contrained variables and explicit types conversion
28+
## Type-constrained variables and explicit types conversion
2929

30-
To _type-constrain_ a variables place a type literal to the left of the
30+
To type-constrain a variable, place a type literal to the left of the
3131
variable name in an assignment. For example:
3232

3333
```powershell
@@ -43,11 +43,11 @@ PS> $var.GetType().Name
4343
Int32
4444
```
4545

46-
This ensures that only values of the specified type can be assigned to the
47-
variable. If you try to assign a value of a different type that can be
46+
Type casting ensures that only values of the specified type can be assigned to
47+
the variable. If you try to assign a value of a different type that can be
4848
converted to the constrained type, PowerShell performs an implicit conversion.
49-
This is covered in more detail in the [Implicit type conversion][15] section of
50-
this article.
49+
For more information, see the [Implicit type conversion][03] section of this
50+
article.
5151

5252
### Numeric type conversion
5353

@@ -67,7 +67,6 @@ Byte
6767
The value `42.1` is a **Double**. When you convert it to a **Byte**, the value
6868
is truncated to an integer `42`, which is small enough to fit into a **Byte**.
6969

70-
7170
### Boolean type conversion
7271

7372
A value of _any_ type can be coerced to a **Boolean**.
@@ -106,11 +105,10 @@ A value of _any_ type can be coerced to a **Boolean**.
106105

107106
### String type conversion
108107

109-
A value of _any_ type can be coerced to a **String**.
110-
111-
The default conversion is to call the `ToString()` method on the object.
108+
A value of _any_ type can be coerced to a **String**. The default conversion is
109+
to call the `ToString()` method on the object.
112110

113-
Array are converted to strings. Each element in the array is converted to a
111+
Arrays are converted to strings. Each element in the array is converted to a
114112
string, individually and joined to the resulting string. By default, the
115113
converted values are separated by a space. The separator can be changed by
116114
setting the `$OFS` preference variable.
@@ -120,10 +118,9 @@ PS> [string] @(1, 2, 3)
120118
1 2 3
121119
```
122120

123-
For more information, see the entry for `$OFS` in
124-
[about_Preference_Variables][12].
121+
For more information about `$OFS`, see [about_Preference_Variables][09].
125122

126-
A single string value can converted to an instance of a type if the type
123+
A single string value can be converted to an instance of a type if the type
127124
implements a static `Parse()` method. For example, `[bigint]'42'` is the same
128125
as `[bigint]::Parse('42', [cultureinfo]::InvariantCulture)`. The optional
129126
`[cultureinfo]::InvariantCulture` value binds to an `IFormatProvider` type
@@ -132,18 +129,18 @@ conversion. Not all implementations of `Parse()` methods have this parameter.
132129

133130
> [!NOTE]
134131
> Conversion to and from strings is usually performed using the
135-
> [invariant culture][04]. Invariant culture is based on, but not identical to,
136-
> the US-English culture. Notably, it uses the periond (`.`) as the decimal
132+
> [invariant culture][16]. Invariant culture is based on, but not identical to,
133+
> the US-English culture. Notably, it uses the period (`.`) as the decimal
137134
> mark and US-style month-first dates by default. However, _binary cmdlets_
138135
> perform culture-sensitive conversion during parameter binding.
139136
140137
### Enum type conversion
141138

142-
PowerShell can convert [System.Enum][03] types to and from **String**
143-
instances. For example, the typecast string `[System.PlatformId]'Unix'` is the
144-
same as the enum value `[System.PlatformId]::Unix`. PowerShell also handles
145-
flag-based enums correctly for comma-separated values inside a string or as an
146-
array of strings. Consider the following examples:
139+
PowerShell can convert [Enum][15] types to and from **String** instances. For
140+
example, the typecast string `[System.PlatformId]'Unix'` is the same as the
141+
enum value `[System.PlatformId]::Unix`. PowerShell also handles flag-based
142+
enums correctly for comma-separated values inside a string or as an array of
143+
strings. Consider the following examples:
147144

148145
```powershell
149146
[System.Reflection.TypeAttributes]'Public, Abstract'
@@ -159,10 +156,12 @@ These examples are equivalent to the enum expression:
159156

160157
### Other type conversions
161158

162-
A single value (non-array) can be converted to an instance of a type if that
163-
type has a (public) single-parameter constructor of the same type (or a type
164-
that the value can be coerced to). For example, the following two lines are
165-
equivalent:
159+
A single value (non-array) can be converted to an instance of a type if:
160+
161+
- That type has a (public) single-parameter constructor
162+
- And the value is same type or can be coerced to the type of the parameter
163+
164+
For example, the following two lines are equivalent:
166165

167166
```powershell
168167
[regex]'a|b'
@@ -179,7 +178,7 @@ and `1.2` is stored as a **Double**. Integers larger than `[Int32]::MaxValue`
179178
are stored as **Int64**. While `42` can be stored as a **Byte** and `1.2` can
180179
be stored as a **Single** type, the implicit typing uses **Int32** and
181180
**Double** respectively. For more information, see
182-
[about_Numeric_Literals][10].
181+
[about_Numeric_Literals][07].
183182

184183
Literal strings are implicitly typed as **String**. Single-character **String**
185184
instances can be converted to and from the **Char** type. However, PowerShell
@@ -195,13 +194,14 @@ These contexts include:
195194
- Expressions using operators
196195
- Boolean contexts - PowerShell converts the conditional expressions of `if`,
197196
`while`, `do`, or `switch` statements to **Boolean** values, as previously
198-
described. For more information, see [about_Booleans][08].
199-
- ETS type definitions - Type conversions can be defined in several ways:
200-
- Using the **TypeConverter** parameter of [Update-TypeData][14]
201-
- In [`Types.ps1xml`][13] files
202-
- In compiled code for types decorated with a [`TypeConverterAttribute`][02]
197+
described. For more information, see [about_Booleans][04].
198+
- Extended Type System (ETS) type definitions - Type conversions can be defined
199+
in several ways:
200+
- Using the **TypeConverter** parameter of [Update-TypeData][12]
201+
- In [Types.ps1xml][10] files
202+
- In compiled code for types decorated with a [TypeConverterAttribute][14]
203203
attribute
204-
- Via classes derived from [`TypeConverter`][01] or [`PSTypeConverter`][06]
204+
- Via classes derived from [TypeConverter][13] or [PSTypeConverter][18]
205205

206206
### Parameter binding conversions
207207

@@ -211,19 +211,19 @@ functions, scripts, scriptblocks, or .NET method where the parameter is
211211
declared with a specific type. Declaring a parameter with the type `[object]`
212212
or not defining a specific type allows any value type to be passed to a
213213
parameter. Parameters can also have custom conversions defined by decorating
214-
parameters with [ArgumentTransformationAttribute][05] attribute.
214+
parameters with [ArgumentTransformationAttribute][17] attribute.
215215

216-
For more information about parameter binding, see [about_Parameter_Binding][11].
216+
For more information, see [about_Parameter_Binding][08].
217217

218-
### Best practices for parameter bindin
218+
### Best practices for parameter binding
219219

220220
For .NET methods, it's better to pass the exact type expected using a type
221221
casts where needed. Without exact types, PowerShell can select the wrong method
222222
overload. And, new method overloads added in future versions of .NET can break
223-
existing code. For an an extreme example of this problem see this
224-
[Stack Overflow question][21].
223+
existing code. For an extreme example of this problem, see this
224+
[Stack Overflow question][11].
225225

226-
If you pass an arrary to a `[string]` typed parameter, PowerShell might convert
226+
If you pass an array to a `[string]` typed parameter, PowerShell might convert
227227
the array to a string as previously described. Consider the following basic
228228
function:
229229

@@ -237,7 +237,7 @@ Test-String -String 1, 2
237237
```
238238

239239
This function outputs `1 2` because the array is converted to a string. To
240-
avoid this behavior, create an advanced function by adding the
240+
avoid this behavior, create an [advanced function][06] by adding the
241241
`[CmdletBinding()]` attribute.
242242

243243
```powershell
@@ -272,28 +272,28 @@ PS> (Get-Date).ToString(@(1, 2))
272272
PowerShell converts the array to the string `"1 2"`, which is passed to the
273273
**Format** parameter of the `ToString()` method.
274274

275-
This is another example of an array conversion problem.
275+
The following example shows another instance of the array conversion problem.
276276

277277
```powershell
278278
PS> $bytes = [byte[]] @(1..16)
279279
PS> $guid = New-Object System.Guid($bytes)
280280
New-Object: Cannot find an overload for "Guid" and the argument count: "16".
281281
```
282282

283-
PowerShell treats the `$bytes` array as a list of individual parameters. even
283+
PowerShell treats the `$bytes` array as a list of individual parameters. Even
284284
though `$bytes` is an array of bytes and `System.Guid` has a `Guid(Byte[])`
285285
constructor.
286286

287-
This very common code pattern is instance of _pseudo method syntax_, which
288-
doesn't always still works as intended. What it translates to is:
287+
This common code pattern is instance of _pseudo method syntax_, which doesn't
288+
always work as intended. This syntax translates to:
289289

290290
```powershell
291291
[byte[]] $bytes = 1..16
292292
New-Object -TypeName System.Guid -ArgumentList $bytes # !! BROKEN
293293
```
294294

295-
Given that `-ArgumentList` is types as `[object[]]`, a _single_ argument that
296-
happens to be an array (of any type) binds to it _element by element_. The
295+
Given that the type of **ArgumentList** is `[object[]]`, a single argument
296+
that happens to be an array (of any type) binds to it _element by element_. The
297297
workaround is to wrap `$bytes` in an outer array so that PowerShell looks for
298298
constructor with parameters that match the contents of the outer array.
299299

@@ -347,7 +347,7 @@ behaviors.
347347
#### Numeric operations
348348

349349
In numeric operations, even if both operands are the same numeric type, the
350-
result may be a different type, due to automatic _type-widening_ to accommodate
350+
result can be a different type, due to automatic _type-widening_ to accommodate
351351
the result.
352352

353353
```powershell
@@ -362,8 +362,8 @@ Double
362362

363363
Even though both operands are integers, the result is _widened_ to a **Double**
364364
to support the fractional result. To get true integer division, use the
365-
`[int][Math]::Truncate()` or `[Math]::DivRem()` static methods. For more
366-
information, see [Truncate()][16] and [DivRem()][17].
365+
`[int]::Truncate()` or `[Math]::DivRem()` static methods. For more
366+
information, see [Truncate()][20] and [DivRem()][19].
367367

368368
In integer arithmetic, when the result overflows the size of the operands,
369369
PowerShell defaults to using **Double** for the results, even when the result
@@ -388,7 +388,7 @@ Int64
388388
```
389389

390390
The `L` suffix on the `1` literal forces the result to be an **Int64**. For
391-
more information, see [about_Numeric_Literals][10].
391+
more information, see [about_Numeric_Literals][07].
392392

393393
Usually, it's the left-hand side (LHS) operand of PowerShell operators that
394394
determines the data type used in the operation. PowerShell converts (coerces)
@@ -401,7 +401,7 @@ PS> 10 - ' 9 '
401401

402402
In this example, the RHS operand is the string `' 9 '`, which is implicitly
403403
converted to an integer before the subtraction operation. The same is true for
404-
the comparision operators.
404+
the comparison operators.
405405

406406
```powershell
407407
PS> 10 -eq ' 10'
@@ -433,15 +433,16 @@ PS> '10' * '2'
433433
1010
434434
```
435435

436-
When you use `[bool]` values with arithmetic operators, PowerShell converts the
437-
values to integers where `$true` becomes `[int]1` and `$false` becomes `[int]0`.
436+
When you use **Boolean** values with arithmetic operators, PowerShell converts
437+
the values to integers: `$true` becomes `[int]1` and `$false` becomes
438+
`[int]0`.
438439

439440
```powershell
440441
PS> $false - $true
441442
-1
442443
```
443444

444-
The one excecption is the multiplication (`*`) of two booleans.
445+
The one exception is the multiplication (`*`) of two booleans.
445446

446447
```powershell
447448
PS> $false * $true
@@ -450,7 +451,7 @@ defined.
450451
```
451452

452453
For other LHS types, arithmetic operators only succeed if a given type
453-
custom-defines these operators via [operator overloading][07].
454+
custom-defines these operators via [operator overloading][02].
454455

455456
#### Comparison operations
456457

@@ -461,7 +462,7 @@ depends on whether the LHS type implements interfaces such as `IEquatable` and
461462

462463
The collection-based comparison operators (`-in` and `-contains`) perform per
463464
element `-eq` comparisons until a match is found. It's each individual element
464-
of the collection operand that drives any type coersion.
465+
of the collection operand that drives any type coercion.
465466

466467
```powershell
467468
PS> $true -in 'true', 'false'
@@ -472,25 +473,25 @@ True
472473

473474
Both examples return true because `'true' -eq $true` yields `$true`.
474475

476+
For more information, see [about_Comparison_Operators][05].
477+
475478
<!-- link references -->
476-
[01]: xref:System.ComponentModel.TypeConverter
477-
[02]: xref:System.ComponentModel.TypeConverterAttribute
478-
[03]: xref:System.Enum
479-
[04]: xref:System.Globalization.CultureInfo.InvariantCulture*
480-
[05]: xref:System.Management.Automation.ArgumentTransformationAttribute
481-
[06]: xref:System.Management.Automation.PSTypeConverter
482-
[07]: /dotnet/csharp/programming-guide/statements-expressions-operators/overloadable-operators
483-
[08]: /powershell/module/microsoft.powershell.core/about/about_Booleans
484-
[09]: /powershell/module/microsoft.powershell.core/about/about_Functions_Advanced
485-
[10]: /powershell/module/microsoft.powershell.core/about/about_Numeric_Literals
486-
[11]: /powershell/module/microsoft.powershell.core/about/about_parameter_binding
487-
[12]: /powershell/module/microsoft.powershell.core/about/about_preference_variables#ofs
488-
[13]: /powershell/module/microsoft.powershell.core/about/about_Types.ps1xml
489-
[14]: /powershell/module/microsoft.powershell.utility/update-typedata
490-
[15]: #implicit-type-conversion
491-
[16]: xref:System.Math.Truncate*
492-
[17]: xref:System.Math.DivRem*
493-
[19]: https://stackoverflow.com/a/76615570/45375
494-
[20]: https://stackoverflow.com/questions/73223637/passing-an-array-parameter-value
495-
[21]: https://stackoverflow.com/questions/76241804/how-does-powershell-split-consecutive-strings-not-a-single-letter
496-
[20816]: https://github.com/PowerShell/PowerShell/issues/20816
479+
[02]: /dotnet/csharp/programming-guide/statements-expressions-operators/overloadable-operators
480+
[03]: #implicit-type-conversion
481+
[04]: about_Booleans.md
482+
[05]: about_Comparison_Operators.md
483+
[06]: about_Functions_Advanced.md
484+
[07]: about_Numeric_Literals.md
485+
[08]: about_parameter_binding.md
486+
[09]: about_preference_variables.md#ofs
487+
[10]: about_Types.ps1xml.md
488+
[11]: https://stackoverflow.com/questions/76241804/how-does-powershell-split-consecutive-strings-not-a-single-letter
489+
[12]: xref:Microsoft.PowerShell.Utility.Update-TypeData
490+
[13]: xref:System.ComponentModel.TypeConverter
491+
[14]: xref:System.ComponentModel.TypeConverterAttribute
492+
[15]: xref:System.Enum
493+
[16]: xref:System.Globalization.CultureInfo.InvariantCulture*
494+
[17]: xref:System.Management.Automation.ArgumentTransformationAttribute
495+
[18]: xref:System.Management.Automation.PSTypeConverter
496+
[19]: xref:System.Math.DivRem*
497+
[20]: xref:System.Math.Truncate*

0 commit comments

Comments
 (0)