11

Is there a way to use operators as functions without declaring them manually?

Func<bool, bool> not = x => !x;

Similar to (+)/(-) in Haskell. Would be handy in various LINQ scenarios involving conditional query construction. Maybe some C# (4.0+) trick I don't know about.

Edit: here is a sample to clarify what I mean:

 int MyWhere(Func<bool, bool, bool> cond) {}

a usual call would be:

MyWhere((x,y) => x && y)

a cool call would be (assuming Haskell style):

MyWhere((&&))
UserControl
  • 14,766
  • 20
  • 100
  • 187
  • What does (+)/(-) do in Haskell? I know C#, but I am not sure what you want to achieve. – Jens Dec 01 '11 at 14:27
  • 2
    + and - are infix operators but can easily be converted into regular functions with () syntax, so instead of 2 + 3 you can write (+) 2 3. – UserControl Dec 01 '11 at 14:29
  • I didn't understand the question. Could you elaborate on this? Preferably with an example? – Nawaz Dec 01 '11 at 14:31
  • What are you really trying to do? In principle you could get the operator method `op_Addition` etc with reflection, but choosing the correct overload is non trivial. – CodesInChaos Dec 01 '11 at 14:31
  • 1
    You _can_ call the operator functions in invocation-style. In IL. I think writing IL code would be good exercise for a while. `call class Program/X class Program/X::op_Addition(class Program/X, class Program/X)` ... – sehe Dec 01 '11 at 14:38

3 Answers3

9

No.

You can find the definitions (F12 in VS) for the operators you can overload, and there exists a

 // struct Double
 public static bool operator ==(double left, double right);

But there is no way to call Double.operator==(a, b).

The Framework does offer a a.Equals(b) for this particualr case, but there is no a.Add(b).

H H
  • 263,252
  • 30
  • 330
  • 514
7

For documentary purposes: user-defined operator are functions, however the C# language explicitly prohibits explicit calls (don't know the rationale). E.g.:

public class X
{
    public static X operator+(X a, X b)
    {
        return new X();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var q = new X() + new X();
        X.op_Addition(q,q); // error CS0571: 
        //   `Program.X.operator +(Program.X, Program.X)': cannot explicitly
        //   call operator or accessor
    }
}

If you were writing IL, you'd write this:

newobj instance void class X::'.ctor'()
newobj instance void class X::'.ctor'()
call class X class X::op_Addition(class X, class X)
stloc.0 
sehe
  • 374,641
  • 47
  • 450
  • 633
1

If i understand what you are want to do right, you can use System.Reflection and Delegate.CreateDelegate to create a delegate to the operator method.

Of course i never testet it, but operator methods are methods so it should work. This could also be automated ( To save time compared to the straight forward method ).

See:

http://msdn.microsoft.com/de-de/library/53cz7sc6.aspx

Community
  • 1
  • 1
Felix K.
  • 6,201
  • 2
  • 38
  • 71