Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell function parameters

Why does the first call to square work, but the second does not:

function add ($arg1, $arg2){
    return $arg1 + $arg2
}

function square ($arg1){
    $arg1 * $arg1
}

Write-Host (square (add 1 2 ))

Write-Host (square (add (1, 2)))
like image 247
Kyle Avatar asked Jun 19 '26 20:06

Kyle


1 Answers

I think you see the problem, but I will post a fuller description for the good of all.

In your first line, your inner call to add is passing two parameters (integers). The function returns an int and the square function squares it.

In the second line, you are passing one array containing two integers. This results in the add function adding one array to nothing and returning an array. Then the square function tries to take that array and multiply it by itself.

You should get an error that looks like this:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".
At line:1 char:8
+ (1,2) * <<<<  (1,2)
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
like image 53
JasonMArcher Avatar answered Jun 22 '26 16:06

JasonMArcher