Creating New Objects (Part 3)

by Dec 15, 2021

While most PowerShell users still use hash tables to create new objects, in the previous tip we introduced classes and their superior type safety. Another benefit are freely definable constructors. This way, you can easily instantiate new objects from your class and at the same time initialize properties with the values you want.

This is what most people do:

$o = [PSCustomObject]@{
    Name = "Tobias"
    Id = 19
    Submission = Get-Date
    Birthday = '1999-02-12 18:33:12' -as [DateTime]

}

$o

With classes you can define a type-safe template and then use new() to instantiate as many new objects as you need:

class Person 
{
    [string]$Name = "Tobias"
    [int]$Id = 19
    [DateTime]$Submission = $(Get-Date)
    [DateTime]$Birthday = $('1999-02-12 18:33:12' -as [DateTime])

} 


$p = [Person]::new()
$p 

However, the new objects either share the same default values you assigned, or you’d have to re-assign each property the values you need.

A better approach is a new constructor like so:

class Person 
{
    [string]$Name = "Tobias"
    [int]$Id = 19
    [DateTime]$Submission = $(Get-Date)
    [DateTime]$Birthday = $('1999-02-12 18:33:12' -as [DateTime])

    # add parameterless default constructor
    Person()
    {}

    # add custom constructor that takes parameters
    Person([string]$Name, [datetime]$Birthday, [int]$Id)
    {
        $this.Name = $Name
        $this.Birthday = $Birthday
        $this.Id = $id
    }
} 


$p = [Person]::new()
$p

$p = [Person]::new('Fred','2020-02-12', 77)
$p

Now you can create new objects as before, or submit the information to new() that you want to use for initialization:

 
PS> [Person]::new()

Name   Id Submission          Birthday           
----   -- ----------          --------           
Tobias 19 26.10.2021 12:28:20 12.02.1999 18:33:12



PS> [Person]::new('Fred','2020-02-03',888)

Name  Id Submission          Birthday           
----  -- ----------          --------           
Fred 888 26.10.2021 12:28:30 03.02.2020 00:00:00    
 


Twitter This Tip! ReTweet this Tip!