tags:

views:

540

answers:

3

I don’t have any experience in F# but have a few lines of test code in C# for a framework I've made that I need to rewrite in F#.

Any help would be appreciated.

    bar.Ready += new Agent.ReadyHandler(bar_Ready);               

    static void bar_Ready(string msg)
    {    
       Console.WriteLine(msg.body);  
    }
+4  A: 

Try this -

bar.Ready.AddHandler(new Agent.ReadyHandler (fun sender msg -> System.Console.WriteLine(msg)))
Matajon
or even shorter: bar.Ready.AddHandler(fun sender msg -> System.Console.WriteLine(msg))
Darin Dimitrov
Note that Delegates in F# do not add the 'BeginInvoke' and 'EndInvoke' methods.
Chris Smith
The same here I get : "The event 'Ready has a non-standard delegate type and must be accessed using the explicit add_Ready and remove_ready methods for the event.", Any idea why?
Ali
+7  A: 

Just to clarify - the shorter version should correctly be:

bar.Ready.Add(fun msg -> System.Console.WriteLine(msg))

Because F# doesn't automatically convert lambda functions to delegates - but there is an Add method that takes a function. This can then be written even simpler like this:

bar.Ready.Add(System.Console.WriteLine)

Because F# allows you to use .NET members as first-class functions.

Tomas Petricek
I get the error: The event 'Ready has a non-standard delegate type and must be accessed using the explicit add_Ready and remove_ready methods for the event.
Ali
A: 

I have played a lot with this and this is the code that work.

bar.add_Ready(fun msg -> Console.WriteLine(msg))

I don't know how theoreticly correct it is but it works fine.

Can any one confirm it is correct?

Ali
Hi, this is correct. Unfortunatelly F# doesn't behave that nicely for all delegates. I think if your delegate followed the standard .NET pattern (XyzEventHandler taking object and XyzEventArgs) then the solutions described above would work too.
Tomas Petricek
BTW: If you're the author of the delegate type and you want to use it only from F#, you may consider using functions instead of delegates.
Tomas Petricek
@Tomas Petricek : The framework itself where the delegate comes from is in C#.
Ali