what is the difference between type "coercion" and "casting" ?

Welcome Forums General PowerShell Q&A what is the difference between type "coercion" and "casting" ?

Viewing 3 reply threads
  • Author
    Posts
    • #190153
      js
      Participant
      Topics: 27
      Replies: 716
      Points: 1,881
      Helping Hand
      Rank: Community Hero

      Is type coercion and type casting the same thing? It sounds more violent, lol. Wny do powershell coders call it coercion?

    • #190168
      Participant
      Topics: 41
      Replies: 167
      Points: 573
      Helping Hand
      Rank: Major Contributor

      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.

    • #190189
      Participant
      Topics: 0
      Replies: 21
      Points: 136
      Helping Hand
      Rank: Participant

      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"
      2
      PS> "1" + 1
      11

      Here is an example of type casting.

      PS> [string]1 + "1"
      11

      PS> [int]"1" + 1
      2

    • #190372
      js
      Participant
      Topics: 27
      Replies: 716
      Points: 1,881
      Helping Hand
      Rank: Community Hero

      Cool. Thanks.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.