Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of how to overload operators with classes in PowerShell.
class Number {
[int] $value = 0
Number() {
#Does nothing.
}
Number([int]$somethingElse) {
$this.value = $somethingElse
}
[void] SetValue([int]$newValue) {
$this.value = $newValue
}
[int] GetValue() {
return $this.value
}
[boolean] Equals($otherNumber) {
if($this.value -eq $otherNumber.GetValue()) {
return $true
} else {
return $false
}
}
static [Number] op_Addition([Number]$first, [Number]$second) {
return [Number]::new($first.GetValue() + $second.GetValue())
}
static [Number] op_Subtraction([Number]$first, [Number]$second) {
return [Number]::new($first.GetValue() - $second.GetValue())
}
static [Number] op_Multiply([Number]$first, [Number]$second) {
return [Number]::new($first.GetValue() * $second.GetValue())
}
static [Number] op_Division([Number]$first, [Number]$second) {
return [Number]::new($first.GetValue() / $second.GetValue())
}
}
#Main code.
$firstNumber = [Number]::new(8)
$secondNumber = [Number]::new(12)
$thirdNumber = [Number]::new(8)
if($firstNumber -eq $secondNumber) {
Write-Output "First and second are equal!"
} else {
Write-Output "First and second are different!"
}
if($firstNumber -eq $thirdNumber) {
Write-Output "First and third are equal!"
} else {
Write-Output "First and third are different!"
}
$fourthNumber = $firstNumber + $secondNumber
Write-Output $fourthNumber.GetValue()
$fifthNumber = $secondNumber - $thirdNumber
Write-Output $fifthNumber.GetValue()
$sixthNumber = $firstNumber * $secondNumber
Write-Output $sixthNumber.GetValue()
$seventhNumber = $sixthNumber / $firstNumber
Write-Output $seventhNumber.GetValue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.