F# infix operators in c#?
Asked Answered
G

1

5

In F# it is not uncommon to declare infix operators for binary operators. But how are they represented if we try to use them in C# Since there are no way of declaring infix operators in C#?

Toy Example

let ( .|. ) a b = a + b
Geis answered 10/12, 2020 at 6:24 Comment(2)
You can’t define new operators in C#, only redefine existing ones like +, -, *, /, <, <<, >>, >, |, &, %, ==, !=, <=, =>.Porshaport
It's worth noting that after a few years of people creating just about any infix operator imaginable, it's now considered poor style to do so without reason. You won't be able to tell what the code is doing when two or more libraries all use the same infix operatorsPaquin
G
9

If you check the IL representation of your operator, you will see this:

 .method public static specialname int32
    op_DotBarDot(
      int32 a,
      int32 b
    ) cil managed

Unfortunately you won't be able to refer to this from C#. However you can add an attribute:

[<CompiledName("addop")>]
let ( .|. ) a b = a + b

Then you can just reference your F# dll from C# and call it via addop:

Console.WriteLine(global::Program.addop(1,2));

3

Process finished with exit code 0.

Goof answered 10/12, 2020 at 12:15 Comment(1)
thanks. I ended up just trying to see it in a toy project, and you can refer to it, but the name for -+- barplusbar or something simular. which are pointless.Geis

© 2022 - 2024 — McMap. All rights reserved.