Paul Biggar
Paul Biggar

Reputation: 28739

How do I write a delegate with params in F#?

I have a C# delegate that I need to replicate in F#:

  public delegate object InvokeDelegate(string method, params object[] parameters)

How do I replicate this in F#?

I tried:

type InvokeDelegate = delegate of (string * (obj [])) -> obj

I'm not sure what's special about this, just that calling the delegate on some library functions doesn't work if I use the F# delegates that I've tried.

I thought it might be the params keyword, but I don't know how to do that in F#.

Upvotes: 0

Views: 248

Answers (1)

Phillip Carter
Phillip Carter

Reputation: 5005

It's a little messy since F# doesn't have params syntax sugar, but here's how you can do it:

open System

type InvokeDelegate = delegate of method: string * [<ParamArray>] parameters: obj [] -> obj

This will compile down into the following C# equivalent delegate:

[Serializable]
[CompilationMapping(SourceConstructFlags.ObjectType)]
public delegate object InvokeDelegate(string method, params object[] parameters);

See here for param arrays: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/parameters-and-arguments#parameter-arrays

And here for delegates: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/delegates

Note that your definition was also a tupled definition (the parentheses did that), compiling down into a delegate with a simple tuple as a parameter. This is probably one of the quirkier areas of F#.

Upvotes: 6

Related Questions