Chapter 15. Events and Delegates: What your code does when you’re not looking
Your objects are starting to think for themselves.
You can’t always control what your objects are doing. Sometimes things...happen. And when they do, you want your objects to be smart enough to respond to anything that pops up. And that’s what events are all about. One object publishes an event, other objects subscribe, and everyone works together to keep things moving. Which is great, until you want your object to take control over who can listen. That’s when callbacks will come in handy.
Ever wish your objects could think for themselves?
Suppose you’re writing a baseball simulator. You’re going to model a game, sell the software to the Yankees (they’ve got deep pockets, right?), and make a million bucks. You create your Ball
, Pitcher
, Umpire
, and Fan
objects, and a whole lot more. You even write code so that the Pitcher
object can catch a ball.
Now you just need to connect everything together. You add an OnBallInPlay()
method to Ball
, and now you want your Pitcher
object to respond with its event handler method. Once the methods are written, you just need to tie the separate methods together:
Note
That’s a commonly used way of naming methods—we’ll talk more about it later.
But how does an object KNOW to respond? ...
Get Head First C#, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.