Simple demonstration of basic features
The following simple example tries to demonstrate the most important and basic features of a user-defined class:
-
class CLS
creates a class, named CLS
- Class members are declared with a type and a name (for example
[int] $num
).
- Static members are introduced with the
static
keyword.
- The constructor has the same name as the class (here:
CLS
) and does not have a return type.
- On the other hand, (member-) methods can have a return type (for example
[string] combineNumAndTxt()
). If a method does not return anything, the type can be omitted or explicitly stated to be [void]
.
- Within methods and the constructor, the instance of the object is referred to by the automatic variable
$this
.
- An object (instance) is created with
$obj = [CLS]::new(…)
(Alternatively, it could be created with the new-object
cmdlet).
- Unlike PowerShell functions and cmdLets, method names cannot have hyphens (and in extension, there are no approved verbs for method names).
Class definition
The definition of a class named CLS
:
set-strictMode -version latest
class CLS {
#
# The class's member variables:
#
[int ] $num
[string] $txt
static [int] $accumulator = 42
#
# The class's constructor:
#
CLS($n, $t) {
$this.num = $n
$this.txt = $t
}
#
# A member method that returns a string.
#
[string] combineNumAndTxt() {
return "$($this.num) - $($this.txt)"
}
#
# A member method that doesn't return
# a value. It's «return type» can be
# explicitely specified as void:
#
[void] printMembers() {
write-host $this.combineNumAndTxt()
}
#
# A static method
#
static [Int] add($x) {
[CLS]::accumulator += $x
return [CLS]::accumulator
}
}
Creating an instance
An instance of a class is created with the
new-object
cmdlet or by using the static method call syntax and the method name
new
:
$obj = [CLS]::new(42, 'hello world')
$anotherObj = new-object CLS 99, 'ninety-nine'
Call methods
A method is called using the object variable followed by a dot and the name of the method:
write-host "obj.num = $($obj.num), obj.txt = $($obj.txt)"
#
# obj.num = 42, obj.txt = hello world
write-host $obj.combineNumAndTxt()
#
# 42 - hello world
$obj.printMembers()
#
# 42 - hello world
Call a static method
A static method is called by putting the class name into square brackets, followed by two colons, followed by the name of the method:
#
# Invoke a static method
#
[CLS]::add(57)
#
# 99
Show type name
$obj.GetType().FullName
#
# CLS
$obj.GetType().BaseType.FullName
#
# System.Object