Let's assume we have these 3 classes:
Class BaseClass : System.IComparable
{
[int] $Value
BaseClass([int] $v)
{
$this.Value = $v
}
[int] CompareTo($that)
{
If (-Not($that -is [BaseClass])) {
Throw "Not comparable!!"
}
return $this.Value - $that.Value
}
}
Class SubClassA : BaseClass
{
SubClassA([int] $v) : base($v)
{
}
}
Class SubClassB : BaseClass
{
SubClassB([int] $v) : base($v)
{
}
}
This implementation works great when we compare instances of BaseClass
:
$base1 = [BaseClass]::new(1)
$base2 = [BaseClass]::new(2)
Write-Output ($base1 -lt $base2)
# Output: True
Write-Output ($base1 -gt $base2)
# Output: False
But I can't find a way to compare two instances of the two subclasses:
$subA1 = [SubClassA]::new(1)
$subB2 = [SubClassB]::new(2)
Write-Output (([BaseClass]$subA1) -lt ([BaseClass]$subB2))
PowerShell can't execute this code, throwing this error:
Impossibile confrontare "SubClassA" con "SubClassB".
Errore:
"Impossibile convertire il valore "SubClassB" di tipo "SubClassB" nel tipo "SubClassA"."
Translated from Italian to English, this error message sounds like:
Unable to compare "SubClassA" with "SubClassB".
Error:
"Unable to convert the value "SubClassB" of type "SubClassB" to the type "SubClassA"."
Why this error?
How can we compare an instance of SubClassA
with an instance of SubClassB
as if they were two instances of BaseClass
?
PS: Output of $PSVersionTable
:
PSVersion 5.1.17134.1
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17134.1
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1