Search code examples
powershellpowershell-5.0

How to nest function call in class method call inline


class TestClass
{
    TestClass([string]$msg) {
        Write-Host "Ctor sees: $msg"
    }
    TestMethod([string]$msg) {
        Write-Host "TestMethod sees: $msg"
    }
}

# this works:
$x = Get-Date
$test1 = [TestClass]::new($x)

# this also works:
$x = Get-Date
$test1.TestMethod($x)

# but doing the same thing inline is a syntax error: Missing ')' in method call.
$test2 = [TestClass]::new(Get-Date)
$test2 = [TestClass]::new(Get-Date())
$test1.TestMethod(Get-Date)

Fairly self-explanatory; I don't want to have to use a temp variable to store arguments before passing them to a method.

I feel that there's just some syntax to make the failing examples work as expected.


Solution

  • The failing tests are missing brackets around Get-Date.

    $test2 = [TestClass]::new((Get-Date))
    

    works because now the result of the Get-Date is evaluated first, and because your class functions want [string], they are automatically stringyfied by PowerShell. Same as when you do

    $test2 = [TestClass]::new((Get-Date).ToString())