Monday, December 28, 2020

PowerShell: Classes Static Constructors, Static Methods, and Static Properties

The previous two posts presented a practical implementation of a static class, PsUnit, in PowerShell (PowerShell: Unit Test Functions and Accessing the Invoking Code's Line Number and PowerShell: Unit Tests Compare Doubles for Equality). A static class does not need to be instantiated in order to invoke its properties and methods.  In .NET one of the most commonly used static classes is the System.Math class that exposes fields such as (shown in their PowerShell form):


The methods of System.Math class include the following:


In PowerShell classes can contain one static constructor that takes no parameters. The static constructor is invoked when the class is first accessed within a script. The first time a method or property of class is invoked, the static constructor is first invoked.

The static constructor for the PsUnit class (introduced in the previous two posts) is as follows on line 12 and is decorated by the keyword static and takes no parameters:

The static constructor shown above is used to initialize the following static properties declared at lines 4, 6, 8, and 10:
  • $filenameLineNumberStart
  • $filenameLineNumberEnd
  • $filenameLineNumberSeparator
  • $boolMismatchMessage
The static methods of the PsUnit class were invoked using the class name, [PsUnit], rather than creating an instance of type PsUnit. Line 36 below shows the IsTrue method of the PsUnit class (a static method) invoking the PsUnit class's static method, CreateMessage:

Line 159 below shows the AreEqual function invoking the AreEqual static method of the PsUnit class:

The code above shows one of the elegant features of PowerShell classes. The methods and properties of a PowerShell class do not pollute the global namespace.  The code [PsUnit]::AreEqual invokes a static method of the PsUnit class. The code below invokes the function AreEqual on lnes 200 to 204:


No comments :

Post a Comment