O'Reilly logo

Head First C#, 2nd Edition by Jennifer Greene, Andrew Stellman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Events and Delegates: What your code does when you’re not looking

image with no caption

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.

Note

That’s a commonly used way of naming methods—we’ll talk more about it later.

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:

image with no caption

But how does an object KNOW to respond? ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required