Comparable object

Viewed 45

How to create comparable objcet via -eq, like .NET object. For example:

class test{
    $a
    $b
    test($a,$b){
        $this.a=$a
        $this.b=$b
    }
}
$obj = [test]::new(4, 5) 
$obj -eq [test]::new(4, 5)
# False

$pt = [System.Drawing.Point]::new(4, 5)
$pt -eq [System.Drawing.Point]::new(4, 5)
# True
1 Answers

Per the documentation:

To create comparable classes, you need to implement System.IEquatable<T> in your class.

class MyFileInfoSet : System.IEquatable[Object] {
    [String]$File
    [Int64]$Size

    [bool] Equals([Object] $obj) {
        return ($this.File -eq $obj.File) -and ($this.Size -eq $obj.Size)
    }
}
$a = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$b = [MyFileInfoSet]@{File = "C:\Windows\explorer.exe"; Size = 4651032}
$a -eq $b
Related