Using Classes (Constructors – Part 5)

by Feb 10, 2017

Classes can have so-called constructors. Constructors are methods that initialize a new object. Constructors are simply methods that share the name of the class. With the help of constructors, it can be much easier to create prepopulated objects. Here is an example: the class “Person” defines a person.

There is a constructor, accepting first and last name, as well as birthday.The constructor is called whenever a new object is instantiated, and prepopulates the object properties:

#requires -Version 5.0
class Person 
{ 
  [string]$FirstName
  [string]$LastName
  [int][ValidateRange(0,100)]$Age
  [DateTime]$Birthday

  # constructor
  Person([string]$FirstName, [string]$LastName, [DateTime]$Birthday)
  {
    # set object properties
    $this.FirstName = $FirstName
    $this.LastName = $LastName
    $this.Birthday = $Birthday
    # calculate person age
    $ticks = ((Get-Date) - $Birthday).Ticks
    $this.Age = (New-Object DateTime -ArgumentList $ticks).Year-1
  }
}

With this class, you can now easily create lists of person objects:

[Person]::new('Tobias','Weltner','2000-02-03')
[Person]::new('Frank','Peterson','1976-04-12')
[Person]::new('Helen','Stewards','1987-11-19')

The result looks similar to this:

 
FirstName LastName Age Birthday              
--------- -------- --- --------              
Tobias    Weltner   16 2/3/2000 12:00:00 AM  
Frank     Peterson  40 4/12/1976 12:00:00 AM 
Helen     Stewards  29 11/19/1987 12:00:00 AM
 

Twitter This Tip! ReTweet this Tip!