Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The C# Workshop

You're reading from   The C# Workshop Kickstart your career as a software developer with C#

Arrow left icon
Product type Paperback
Published in Sep 2022
Publisher Packt
ISBN-13 9781800566491
Length 780 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Almantas Karpavicius Almantas Karpavicius
Author Profile Icon Almantas Karpavicius
Almantas Karpavicius
Jason Hales Jason Hales
Author Profile Icon Jason Hales
Jason Hales
Mateus Viegas Mateus Viegas
Author Profile Icon Mateus Viegas
Mateus Viegas
Arrow right icon
View More author details
Toc

Events or Delegates?

On the face of it, events and delegates look remarkably similar:

  • Events are an extended form of delegates.
  • Both offer late-bound semantics, so rather than calling methods that are known precisely at compile-time, you can defer a list of target methods when known at runtime.
  • Both are called using Invoke() or, more simply, the () suffix shortcut, ideally with a null check before doing so.

The key considerations are as follows:

  • Optionality: Events offer an optional approach; callers can decide to opt into events or not. If your component can complete its task without needing any subscriber methods, then it is preferable to use an event-based approach.
  • Return types: Do you need to handle return types? Delegates associated with events are always void.
  • Lifetime: Event subscribers typically have a shorter lifetime than their publishers, leaving the publisher to continue detecting new messages even if there are no active subscribers...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime