Skip to content

Instantly share code, notes, and snippets.

@chgeuer
Last active June 24, 2020 20:59
Show Gist options
  • Save chgeuer/c58555ca1b0b27a163c9022706985f8c to your computer and use it in GitHub Desktop.
Save chgeuer/c58555ca1b0b27a163c9022706985f8c to your computer and use it in GitHub Desktop.

Interfaces defined in F# and used from C#

For a customer project, I needed to define an interface, and an implementation of that interface, implementing a factory. I wanted to pass in a creation lambda (from C#) to the factory, and the Create() function under the hood should invoke the lambda.

Wrong - The interface defines a property, which returns a Func.

open System

type ICSharpPropertyFuncFactory<'t> =
    abstract member Create : Func<'t>

type CSharpPropertyFuncFactory<'t> (createPipeline) =
    interface ICSharpPropertyFuncFactory<'t> with
        member _.Create = createPipeline
Func<string> f = () => Guid.NewGuid().ToString();

//public interface ICSharpPropertyFuncFactory<t>
//{
//    Func<t> Create { get; }
//}
ICSharpPropertyFuncFactory<string> csharpPropertyFuncFactory = new CSharpPropertyFuncFactory<string>(f);
Console.WriteLine(csharpPropertyFuncFactory.Create());

The right way

open System

type IFSharpFactory<'t> =
    abstract member Create : unit -> 't

type FSharpFactory<'t> (f : Func<'t>) =
    interface IFSharpFactory<'t> with
        member _.Create () = f.Invoke()
Func<string> f = () => Guid.NewGuid().ToString();

//public interface IFSharpFactory<t>
//{
//    t Create();
//}
IFSharpFactory<string> fSharpFactory = new FSharpFactory<string>(f);
Console.WriteLine(fSharpFactory.Create());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment