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 

  # 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:


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!