Urgent.News

600+ sources. One page. See who else covered it.

Editions

Tech

Delete the Event Switch: Runtime Dispatch with dynamic in C#

A switch over event types is dynamic dispatch. You just wrote it by hand, took on the maintenance yourself, and skipped the help the runtime was ready to give you. You've written this method. Every event-driven codebase has one: public Task HandleAsync ( BaseEvent @event ) => @event switch { OrderPlaced e => HandleAsync ( e ), PaymentFailed e => HandleAsync ( e ), InventoryReserved e =>…

Dynamic dispatch is achieved through runtime type-based method selection. Writing this manually involves adding code for each event type, which is prone to errors and maintenance issues. The provided C# code demonstrates a cleaner approach using dynamic casting at a single point in the code. By casting the event to dynamic at the boundary, the C# runtime binder automatically selects the appropriate handler method based on the event's runtime type.

The code defines a hierarchy of domain events as sealed records inheriting from a base BaseEvent class. A processor class, EventProcessor, handles these events by casting them to dynamic within a single handler method, HandleAsync. The method delegates the actual handling to three overloaded private methods, Dispatch, each corresponding to a specific event type. A fallback method handles any unhandled event types, throwing a NotSupportedException with a descriptive message.

The dynamic casting enables the compiler to select the most specific handler method at runtime, eliminating the need for manual switch statements and reducing maintenance overhead. While the runtimeBinderException thrown for unrecognized event types may seem confusing, the fallback handler provides a clear, user-defined error message.

Dynamic casting does not impact performance significantly, as the runtime cache the results of the dispatch for each event type. However, it is essential to ensure null checks and proper return types to avoid runtime errors. By delegating the event handling to the runtime, developers can focus on writing specific handlers for each event type, leading to cleaner, more maintainable code.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — it may contain errors, so check the original before relying on it.

Read the original at dev.to →

More in Tech

The Developer Who Put an OS on the Amiga — Tim King (1947–2026)

A Cambridge Student Writes an Operating System In the late 1970s, a Cambridge computer science student named Tim King needed an operating system for the Cambridge LISP machine.

  • Tim King, born in 1947, created Tripos, a preemptive multitasking OS in BCPL.
  • King joined MetaComCo in 1984, bringing Tripos to Commodore for Amiga development.
  • King founded Perihelion and UK Online, shaping modern computing concepts.