Alan Wayne
Alan Wayne

Reputation: 5384

How to write an Event member for an F# interface?

I am new to F#. In C#, I have an interface defined as:

public interface IMenuEvents
   {
       event Action SaveEvent;
       event EventHandler<ParagraphReadyEventArgs> ParagraphReadyEvent;

       ....
   }

where

public class ParagraphReadyEventArgs : System.EventArgs
    {
        public ParagraphReadyEventArgs(string paragraph_title)
        {
            ParagraphTitle = paragraph_title;
        }

        public string ParagraphTitle { get; }
    }

How is the interface IMenuEvents written in F# ?

Thank you for any help.

Upvotes: 0

Views: 93

Answers (1)

JL0PD
JL0PD

Reputation: 4488

Given declaration translates to

open System

type ParagraphReadyEventArgs(paragraphTitle: string) =
    inherit EventArgs()
    member val ParagraphTitle = paragraphTitle

type IMenuEvents =
    [<CLIEvent>]
    abstract member SaveEvent : IDelegateEvent<EventHandler>

    [<CLIEvent>]
    abstract member ParagraphReadyEvent : IDelegateEvent<EventHandler<ParagraphReadyEventArgs>>

Key difference is that EventHandler wrapped inside IDelegateEvent<T>

Behind the scenes you get same interface that you could get with C#. Decompilation

I don't understand why F# chose to make things that complicated yet. Hope somebody have an answer for this question

Few words about original design: It's recommended for all events to have type EventHandler or EventHandler<TEventArgs>, don't use custom event types. If you concern about memory allocation from EventArgs, then use EventArgs.Empty instead of new EventArgs()

Upvotes: 1

Related Questions