Case sensitiveness
These operators, if used on strings, are case insensitive by default. In order to make them case sensitive, they need to be prefixed with a c
(for example -ceq
or -cgt
)
It's also possible to explicitly state case sensitive comparison by prefixing the operator name with an i
(for example -ieq
).
Scalar vs array
The operators -eq
, -ne
, -gt
, -lt
, -le
, -ge
and their case sensitive cousins return a boolean if applied to a scalar.
4 -gt 2
#
# True
4 -gt 5
#
# False
4, 6, 3, 5, 7 -gt 4 -join ', '
#
# 6, 5, 7
Comparing objects
If the compared
objects don't implement the
System.IComparable
interface,
-eq
and
-ne
checks whether the expressions (typically
variables) on either side of the operator refer to the same object:
class C {
[Int32] hidden $val
C($v) {
$this.val = $v
}
}
$obj_1 = [C]::new(4)
$obj_2 = [C]::new(2)
$obj_3 = [C]::new(4)
$obj_4 = $obj_1
$obj_1 -eq $obj_4 # $obj_1 and $obj_4 refer to the same object -> operator returns $true
$obj_1 -eq $obj_3 # $obj_1 and $obj_3 refer to different objects -> operator returns $false
Required methods and interfaces
If a class does not implement IComparable
and an instance of such a class is compared with for example -eq
, the environment throws the error message Cannot compare "…" because it is not IComparable.
The following example defines a
class (named
C
) which implements
IComparable
and then creates a few instances of it and compares with
-lt
,
-gt
and
-eq
.
class C : IComparable {
[int] hidden $val
C([int] $v) {
$this.val = $v
}
[bool] Equals([Object] $other) {
#
# Equals() is required for the -eq operator.
#
return $this.val -eq $other.val
}
[int] CompareTo([Object] $other) {
#
# CompareTo() is required for the -lt
# and -gt operator.
#
return $this.val - $other.val
}
[int] GetHashCode() {
#
# An object that overrides the Equals() method
# should (must?) also override GetHashCode()
#
return $this.val
}
}
$four = [C]::new(4)
$seven = [C]::new(7)
$VII = [C]::new(7)
$four -lt $seven # True
$four -gt $seven # False
$four -eq $seven # False
$seven -eq $seven # True
$seven -eq $VII # True
The comparison of
$seven -eq $VII
returns
$true
although these
variables don't refer to the same
object. Thus, it demonstrates that
-eq
does not test for
identity (such as for example the
Python operator is
).