// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript). // provenance: events.es topic: delegates-events status: verified // hand-authored, idiomatic E# — verified through the E# compiler namespace Demo // ═════════════════════════════════════════════════════════════════════════════ // Events — a controlled subscription point over a delegate. The delegate is the payload; // the event only governs who may subscribe (`+=`) and unsubscribe (`-=`). Outside code // can't invoke or replace it. Events are declared on `ref data` (they imply identity), // fired with the null-safe `raise` statement, and emit exactly what C# emits for // `public event Action OnChanged;` — so a C# consumer subscribes with `+=` unchanged. // ═════════════════════════════════════════════════════════════════════════════ // A counter that announces every change. `event OnChanged: Action` declares the // subscription point, typed by the `Action` delegate. ref data Counter { var total: int event OnChanged: Action init() { self.total = 0 } func add(n: int) { self.total = self.total + n // `raise` captures the handler list then invokes it — a no-op when there are no // subscribers, and safe against a handler unsubscribing mid-raise. raise OnChanged(self.total) } } func main() -> int { var lastSeen = 0 // mutable local, captured by the handler below let c = Counter() // Subscribe a lambda whose shape matches the event's Action. Closures capture // outer `var`s mutably, so each raise writes the new total back into `lastSeen`. c.OnChanged += func(v: int) -> void { lastSeen = v } c.add(5) // total 5 → OnChanged(5) → lastSeen = 5 c.add(3) // total 8 → OnChanged(8) → lastSeen = 8 return lastSeen // 8 — proof the event fired and the handler ran }