views:

127

answers:

2

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

+3  A: 

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
Roman Kuzmin
+4  A: 

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.

stej