Using F# from C#

Let’s take a simple example – we have a library in F# which has functions that we want to use in C#. In this case we’ve got a Fibonacci function.

  1. Create a C# console application (for this demo)
  2. Add a new F# Library project (I named mine FLib)
  3. Add the following code to the library
    namespace FLib
    
    module Mathematics =
    
        let rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)
    

    Note: you must include the module if you want to declare values/functions in a namespace

  4. Now in the C# application add the using clause

    using FLib;
    
  5. And finally we use the function as per the following
    int result = Mathematics.fib(5);
    

    The module appears list a static class with static methods.