Click here to Skip to main content
15,887,436 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
How we can call F# functions from C# coding.
Posted

Start here: Call F# code from C#[^].

Google is your friend.
 
Share this answer
 
1) Add a reference FSharp.Core dll in your project
2) Reference Microsoft.FSharp.Core namespace in your code
using FS = Microsoft.FSharp.Core;


3) Implement your function, for example:

C#
public static IEnumerable<U> map<T, U>(FS.FSharpFunc<T, U> mapper, 
 IEnumerable<T> input)
{
    foreach (T el in input)
    {
        yield return mapper.Invoke(el);
    }
}




Note: there are differences depending on the version of the .Net runtime
(4.0 vs. 3.5)
Bonus: return F# functions from C# code.

You can also implement F# functions in C# code and pass them to F#
//this is unit->string in F# speak
public class ReturnString: FSharpFunc<Unit, string>
{
    public FSharpFunc<Unit,string> asFSharpFunc()
    {
        return this;
    }

    public override string Invoke(Unit unitVar0)
    {
        return "a string";
    }
}


In F# do:
let funcFromCSharp = (ReturnString()).asFSharpFunc() //get it
funcFromCSharp () //call it


or this
let inline toFunc<'a,'b,'c when 'c :> FSharpFunc<'a,'b>> (x: 'c ): ('a -> 'b) = (# "" x : 'a -> 'b #)

let funcFromCSharp = ReturnString()|> toFunc
funcFromCSharp () //call it
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900