views:

173

answers:

2

First part: call F# from F#

Let's say we have the following type defined in F#:

type MyClass =
    static member Overload1 (x, y) = "Pim"
    static member Overload1 (x : System.Tuple<_, _>) = "Pam"
    static member Overload1 x = "Pum"

You are now in another module (in another file).

How can you call each of the three methods shown above?

Second part: call C# from F#

Now, you define a class in C#:

public class MyClass {
    public static string Overload1<a, b>(a x, b y) { return "Pim"; }
    public static string Overload1<a, b>(Tuple<a, b> x) { return "Pam"; }
    public static string Overload1<a>(a x) { return "Pum"; }
}

From a F# code, how can you call each of the three methods now defined in C#?

+4  A: 

Hmm, I am unclear if it is possible to call the F# "Pam" method. But here's the rest.

C#:

using System;
namespace CSharp
{
    public class MyClass
    {
        public static string Overload1<a, b>(a x, b y) { return "Pim"; }
        public static string Overload1<a, b>(Tuple<a, b> x) { return "Pam"; }
        public static string Overload1<a>(a x) { return "Pum"; }
    }
}

F#:

namespace FSharp

type MyClass =
    static member Overload1 (x, y) = "Pim"
    static member Overload1 (x : System.Tuple<_, _>) = "Pam"
    static member Overload1 x = "Pum"

namespace DoIt

module Examples =
    let CallFSharp() =
        printfn "%s" <| FSharp.MyClass.Overload1(1,2)   // Pim
        printfn "%s" <| FSharp.MyClass.Overload1((1,2)) // Pum!
        printfn "%s" <| FSharp.MyClass.Overload1(())    // Pum


    let CallCSharp() =
        printfn "%s" <| CSharp.MyClass.Overload1(1,2)             // Pim
        printfn "%s" <| CSharp.MyClass.Overload1<int,int>((1,2))  // Pam
        printfn "%s" <| CSharp.MyClass.Overload1(())              // Pum

    do
        CallFSharp()        
        CallCSharp()        

Of course, in practice it will be rare to see methods in IL that take System.Tuple<...> objects as parameters.

Brian
+2  A: 

Here's an answer to the F# part:

MyClass.Overload1(1,2)
MyClass.Overload1<_,_>(unbox (box (1,2)) : System.Tuple<int,int>)
MyClass.Overload1 1
kvb
Wow! What a hack! Good!
Bruno Reis