Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does -eq keyword in power shell test reference equality or use Object.Equals()

Does "-eq" in Powershell test reference equality (like "==" in c#) or does it do the equivalent of calling Object.Equals()

like image 765
Willbill Avatar asked Apr 28 '10 13:04

Willbill


2 Answers

The test on equality is not so simple.

Consider that 'a' -eq 'A' returns true. That means that PowerShell does something more than just call Equals.

Further for your objects Equals is called as expected.

Add-Type -TypeDefinition @"
    using System;
    public class X {
        public string Property;
        public X(string s) {
            Property = s;
        }
        public override bool Equals(object o) {
            System.Console.WriteLine("equals on {0}", Property);
            return Property == ((X)o).Property;
        }
        public override int GetHashCode() { return 20; }
    }
"@

$o1 = New-Object X 'a'
$o2 = New-Object X 'A'

$o1 -eq $o2

Besides that PowerShell uses conversion quite heavily. So if the operands are not of the same type, the right operand is converted to the type of the left operand. That's why '1' -eq 1 succeeds.

like image 121
stej Avatar answered Sep 20 '22 05:09

stej


The operator -eq is none of (like "==" in c#) and Object.Equals(). Simple example: it performs case insensitive string comparison. In fact, it performs a lot of conversions under the covers and some of them, unfortunately, might be not even always intuitively expected.

Here is some interesting demo

# this is False
[ConsoleColor]::Black -eq $true

# this is True
$true -eq [ConsoleColor]::Black
like image 23
Roman Kuzmin Avatar answered Sep 22 '22 05:09

Roman Kuzmin