Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events and Delegates in F#

Tags:

c#

.net

f#

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);  
    }
like image 378
Ali Avatar asked Feb 15 '09 11:02

Ali


2 Answers

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.

like image 168
Tomas Petricek Avatar answered Oct 07 '22 18:10

Tomas Petricek


Try this -

bar.Ready.AddHandler(new Agent.ReadyHandler (fun sender msg -> System.Console.WriteLine(msg)))
like image 20
Martin Jonáš Avatar answered Oct 07 '22 17:10

Martin Jonáš