Aaron Anodide
Aaron Anodide

Reputation: 17186

how to create a function that takes a function as a parameter?

This is just an experienting/learning example. I'm an extreme functional noob.

F# code to be used from C#:

module C
open System
open System.Collections.Generic
let Log format (f:Action<List<Object>>) =
    let arguments = f.Invoke(new List<Object>())
    let message = String.Format(format, arguments)
    Console.Write(message)

C# code that calls it:

   C.Log("Hello {0}", c =>
       {
          c.Add("World");
       });

Expected Result

Hello World

Actual Result

Hello

Upvotes: 1

Views: 143

Answers (1)

JaredPar
JaredPar

Reputation: 754585

The problem is you are creating a new List<Object> and passing it to an Action<T>. An Action<T> delegate doesn't return any values hence you never get this list back. Instead the Invoke method just returns null which is ignored in the String.Format call. You need to persist the list between the delegate invoke and String.Format

Try the following

let list = List<Object>();
f.Invoke(list);
let message = String.Format(format, list.ToArray());

Upvotes: 3

Related Questions