EricP
EricP

Reputation: 502

Subscribing to c# Events in F# With Partial Applications

I have this working after a few hours of bashing my head. Now I'm trying to understand why.

This is an event definition from a c# lib:

internal readonly AsyncEvent<Func<SocketMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<SocketMessage, Task>>();

The only way it works is by passing in a (fun -> ) directly:

        helper.client.add_MessageReceived
            (fun msg ->
                processMsg msg)

It cannot be parameterized:

        let x = 
            (fun msg ->
                processMsg msg)
        
        helper.client.add_MessageReceived x

I initially tried to just pass the processMsg function. It looked like the right signature:

        helper.client.add_MessageReceived processMsg

Upvotes: 0

Views: 120

Answers (1)

Nghia Bui
Nghia Bui

Reputation: 3784

That's because System.Func is a delegate.

When you pass a lambda function to add_MessageReceived, the lambda is implicitly converted to a System.Func.

But in other cases, you need to explicitly do the converting:

let x = System.Func<_, _> (fun msg -> processMsg msg)
helper.client.add_MessageReceived x

Upvotes: 1

Related Questions