views:

97

answers:

3

How can one create an object that when its operators, such as:

operator > (Object obj1, Object obj2)  
operator < (Object obj1, Object obj2)

, are overridden PowerShell utilizes these operators?

Such that:

where-object { $CustomObject -gt 12 } 

would call:

public static bool operator > (Object object1, Object object2)

Is it possible?

To clarify:

  • The object exists within a .NET assembly
  • The object has overridden comparision operators
  • PowerShell does not seem to honor these operators
A: 

I do not believe you can do operator overloading in Powershell.

GrayWizardx
Yeah I'm seeing the same thing. It would be cool if I could utilize overridden comparison operator :\
Adam Driscoll
If he is attempting to "create a .NET object" (presumably in C# or VB) why would he need to override operators in PowerShell when it can be done easily in C# or VB?
Keith Hill
A: 

You cannot do operator overloading in PowerShell, but I believe the way you've declared it will work as PowerShell should obey the operator overloading of .NET. When this does not work what you are often seeing is different objects on each side, i.e. a [int] -gt [string]. You can always try explictly casting both of the objects before a comparison.

Hope this helps

Start-Automating
+5  A: 

PowerShell is using the IComparable interface to compare objects. At least, this is what the following little experiment shows:

$src = @'
using System;
namespace Acme 
{
    public class Foo : IComparable
    {
        public Foo(int value)
        {
            this.Value = value;
        }

        public int Value { get; private set; }

        public static bool operator >(Foo foo1, Foo foo2)
        {
            Console.WriteLine("In operator >");
            return (foo1.Value > foo2.Value);
        }

        public static bool operator <(Foo foo1, Foo foo2)
        {
            Console.WriteLine("In operator <");
            return (foo1.Value < foo2.Value);
        }

        public int CompareTo(object obj)
        {
            Console.WriteLine("In CompareTo");
            if (obj == null) return 1;

            Foo foo2 = obj as Foo;
            if (foo2 == null) throw new ArgumentException("Not type Foo","obj");

            if (this.Value == foo2.Value)
            {
                return 0;
            }
            else if (this.Value > foo2.Value)
            {
                return 1;
            }
            else 
            {
                return -1;
            }
        }
    }
}
'@

Add-Type -TypeDefinition $src -Language CSharpVersion3

$foo1 = new-object Acme.Foo 4
$foo2 = new-object Acme.Foo 8

$foo1 -gt $foo2
In CompareTo
False
Keith Hill