Is type coercion and type casting the same thing? It sounds more violent, lol. Wny do powershell coders call it coercion?
If I understand correctly, Casting is when you explicitly change data from one to type to another.
Coercion is when you leave the compiler to decide which type to use when different types are encountered. eg: with Tsql when there are varchar and nvarchar values, the nvarchar has a higher precedence and so all varchar values are converted to nvarchar to carryout a comparison. That’s coercion.
As Iain said, casting is explicit type conversion. Coercion is implicit type conversion.
Here is an example of coercion in action. PowerShell evaluate the expression left-to-right. In the first case, the left-most value is of type [int] so the string is coerced to that type. In the second case, the the left-most value is of type [string].
PS> 1 + “1”
PS> “1” + 1
Here is an example of type casting.
PS> [string]1 + “1”
PS> [int]“1” + 1