Inject F # interface member with return type in C #

Suppose I defined the following interface in F #:

type IFoo<'T> = abstract member DoStuff : 'T -> unit 

If I implement this in C #, I need a method signature:

 public void DoStuff<T>(T arg) {...} 

What I really want to do is link FSharp.Core and then use:

 public Unit DoStuff<T>(T arg) {...} 

This will simplify the other code because I do not have to deal with Action vs Func. I assume there is no pure way to achieve this? What about evil hacks?

+4
null f # unit-type
source share
1 answer

Converting Unit to void baked into the compiler. There's a FuncConvert class in F # Core to convert between FSharpFunc and Converter . What about defining a similar class to convert Action<T> to Func<T, Unit> ?

 static class ActionConvert { private static readonly Unit Unit = MakeUnit(); public static Func<T, Unit> ToFunc<T>(Action<T> action) { return new Func<T, Unit>(x => { action(x); return Unit; }); } private static Unit MakeUnit() { //using reflection because ctor is internal return (Unit)Activator.CreateInstance(typeof(Unit), true); } } 

Then you could do

 var foo = new Foo<int>(); var func = ActionConvert.ToFunc<int>(foo.DoStuff); 

Perhaps you can even discard the Unit instance and return null .

+4
source share

All Articles