Splatting a class constructor

Welcome Forums General PowerShell Q&A Splatting a class constructor

This topic contains 3 replies, has 4 voices, and was last updated by

 
Participant
3 weeks, 1 day ago.

  • Author
    Posts
  • #173641

    Participant
    Topics: 15
    Replies: 13
    Points: 54
    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: 100
    Points: 363
    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: 25
    Replies: 678
    Points: 1,629
    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: 483
    Points: 1,152
    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. 🙂

     

You must be logged in to reply to this topic.