C#: Events

I still find it all quite unintuitive…accepting that by its nature the Publisher/Subscriber pattern is not designed with intuition uppermost in one’s mind.

I deal in pictures, so to give some concrete expression to this, I thought of a few things that would maintain a movie in my head of the events and handlers playing out.

  • SuperMario falling off a wall – where the random arguments from the event of hitting the ground dictate what type of ground he falls on – if concrete then he dies, if a mattress, OK etc
  • Sniper randomly firing at people at specific coordinates. If the random ballistic coordinates matches a person’s position, then… you get the picture. Nah, not my style.
  • A simple ball game, where similarly to the previous one, a person at specific coordinates does or does not catch the random ball throw. We’ll go with that, but for this phase, all we will do is tell the subscriber that the ball has been thrown… and then that the game has ended.

It is a console application, it has a Program.cs (subscriber) which instantiates the BallGame and its events (publisher). Although its useful to see examples of the Delegate keywords in practice, to understand how we get from that to [event] and EventHandler… I’m not going to do that.

So we have the BallGame class, with some messages to emphasise that it is the Publisher:

BallGame01

There is the EventArgs class, as the preferred way of passing event data around…

BallGame02

And lastly the client code:

BallGame03

The execution of the program:

BallGame04

Pastebin here here here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s