Splatting a class constructor

Is it possible to utilize splatting when constructing an object from a custom class? I get an error when I try it. But I thought maybe theres some other way.

 

class n {
$first
$last
n ($first,$last) {
$this.first = $first
$this.last = $last
}
}
$d = @{
first='Bob';Last='Evans'
}
[n]::new($d)

Hello Brian,

To use splatting in PowerShell you must use the at symbol (@) not the dollar sign ($). Unfortunately for a class it doesn’t appear possible to use the splatting method. And is still under consideration from Microsoft.

https://github.com/PowerShell/PowerShell/issues/4038

It works this way, casting a hashtable.

class n {
  $first
  $last
}

$d = @{
  first='Bob';Last='Evans'
}

[n]$d


first last
----- ----
Bob   Evans

Yep, casting a hashtable to a class type will always work if:

  1. the type has a public parameterless constructor
  2. the members you're trying to set with the hashtable are public and settable
Both of these are presently always true for classes constructed with PS's class syntax. However, it also works for any .NET types that satisfy those constraints. :)