Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Example: Getting Data Back from an EventHandler

0.00/5 (No votes)
18 Sep 2013 1  
Getting data back from an EventHandler.

Background

I previously wrote about why I like to use events here and here. I figured it would be appropriate to illustrate a simple case where you can delegate decisions between functionally separate parts of code (say, between an application layer and a presentation layer). If you're well versed in C# and .NET, this might put you to sleep. If you have no idea what I'm talking about, hopefully this will help.

The Scenario

Let's assume we have a layered application, which is usually my go to. I might have three layers: one for data persistence, one for my business logic and one for interacting with the user. I'll call these the data, application, and presentation layers, respectively. Let's also assume that the dependency flow works from the top layer down (so presentation layer depends on application and data, and application depends on data). Nice.

In my application layer, I have a class that can process data. Specifically, it can capitalize an input string and spit out the capitalized output. However, some input characters are not letters A-Z or a-z... So how should our processor behave? Let's have it delegate this decision to the user (who interacts with the presentation layer) and get back our result.

The Workflow

The following is the workflow for the application:

  • Create a processor object
  • Hook on the event handler so that the presentation layer can handle the corresponding event
  • Start processing the input
    • Capitalize valid characters
    • When we reach an invalid character...
      • Call our data processor's event to delegate the work to anyone who can make the decision for us (in this case, our presentation layer)
      • Have the event handler (the presentation layer) ask the user if we should skip the input
      • Store the result back on the event args
      • Back in the processor class, based on the result of the event args, we can skip or add the character.

Summary

It's a pretty straight forward task really. Because event args are objects in C#, we can store state on them and pass them around easily. If they were value types, we'd have to rely on function calls to return the user's decision as to whether or not we should skip the input. In my opinion, this is a bit uglier (but certainly still doable).

I've created a sample project and hosted it at Google Code, here. Check it out!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here