Welcome Forums General PowerShell Q&A Splatting a class constructor

Viewing 3 reply threads
  • Author
    Posts
    • #173641
      Participant
      Topics: 16
      Replies: 14
      Points: 67
      Rank: Member

      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)
    • #173644
      Participant
      Topics: 0
      Replies: 115
      Points: 433
      Helping Hand
      Rank: Contributor

      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

    • #173683
      js
      Participant
      Topics: 28
      Replies: 752
      Points: 2,102
      Helping Hand
      Rank: Community Hero

      It works this way, casting a hashtable.

      class n {
        $first
        $last
      }
      
      $d = @{
        first='Bob';Last='Evans'
      }
      
      [n]$d
      
      
      first last
      ----- ----
      Bob   Evans
      
    • #173737
      Participant
      Topics: 2
      Replies: 512
      Points: 1,309
      Helping Hand
      Rank: Community Hero

      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. 🙂

       

Viewing 3 reply threads
  • The topic ‘Splatting a class constructor’ is closed to new replies.