Constructor chaining in PowerShell - call other constructors in the same class Constructor chaining in PowerShell - call other constructors in the same class powershell powershell

Constructor chaining in PowerShell - call other constructors in the same class


To complement Mathias R. Jessen's helpful answer:

The recommended approach is to use hidden helper methods to compensate for the lack of constructor chaining:

Class car {    [string]$Make    [string]$Model    [int]$Year    speedUp (){        $this.speedUp(5)    }    speedUp ([int]$velocity){        $this.speed += $velocity    }    # Hidden, chained helper methods that the constructors must call.    hidden Init([string]$make)                 { $this.Init($make, $null) }    hidden Init([string]$make, [string]$model) { $this.Init($make, $model, 2017) }    hidden Init([string]$make, [string]$model, [int] $year) {        $this.make = $make        $this.model = $model        $this.Year = $year    }    # Constructors    car () {        $this.Init('Generic')    }    car ([string]$make) {        $this.Init($make)    }    car ([string]$make, [string]$model) {        $this.Init($make, $model)    }    car ([string]$make, [string]$model, [int]$year) {         $this.Init($make, $model, $year)    }}[car]::new()                          # use defaults for all fields[car]::new('Fiat')                    # use defaults for model and year[car]::new( 'Nissan', 'Altima', 2015) # specify values for all fields

This yields:

Make    Model  Year----    -----  ----Generic        2017Fiat           2017Nissan  Altima 2015

Note:

  • The hidden keyword is more of a convention that PowerShell itself observes (such as omitting such members when outputting); members tagged this way are technically still accessible, however.

  • While you can't call a constructor of the same class directly, it is possible to do so with a base-class constructor, using C#-like syntax.


TL;DR: No!


What you're looking for (overloaded constructors calling each other in succession) is also colloquially known as constructor chaining, and looks roughly like this in C#:

class Car{    string Make;    string Model;    int Year;    Car() : this("mall", null)    {    }    Car(string make, string model) : this(make, model, 2017)     {    }    Car(string make, string model, int Year)     {         this.Make = make;        this.Model = model;        this.Year = year;    }}

Unfortunately, PowerShell doesn't seem to have any syntax for this - you can't do:

Car() : $this("Porsche") {}Car([string]$Make) {}

without having the parser throw up at you for missing the body definition of your constructor, and I don't expect to see it anytime soon - the PowerShell team has expressed an explicit desire not to become the maintainers of a new watered down C# - which I can perfectly well understand :-)

You'll just have to re-implement the member assignments in each constructor definition.