651.288.7000 info@intertech.com

Understanding C# Events

C# Tutorial: Understanding C# Events
— Intertech, Inc. —
I am surprised how often C# developers are confused about delegates and events. They sometimes forget how all C# events are based on delegates and what the delegates offer for C# events. As well, some are confused about how to publish and subscribe to events and how to pass information when raising an event from a publisher to subscriber.
In this C# event tutorial, I will explain how delegates are the foundation for C# events and show the two primary delegates that Microsoft has given us for creating our own events. I will also show you how to subscribe to your own events and even pass data back to the event handlers.

What
Delegates Do

Every single event in .NET, whether Microsoft created it or if it was created by someone else, is based on a .NET delegate. Delegates are one of the five types of types included with .NET – class, structure, interface, enumeration, and delegate.

At its foundation, delegates do two things:

  1. When created, it points to a method (instance or static) in a container (class or structure). For events, it points to an event hander method.
  2.  

  3. It defines exactly the kind of methods that it can point to, including the number and types of parameters and also the return type.

Definition of a
Simple Delegate

Here is a definition of a simple delegate. It can be declared at the namespace level, meaning it doesn’t need to be nested in a class. The delegate below can only point to a method that accepts two integer parameters and returns an integer. Interestingly, the parameters “a” and “b” are never used directly, but they are required to define the delegate.
You can create an instance of the delegate pointing to a method. Then, every time you call the delegate, it calls the method for you. If the method returns a value, the delegate returns it for you. Here’s a complete simple example.
As useless and redundant as the code appears, delegates can be set at run time rather than design time. This adds flexibility to our code. We can assign methods as our app is running based on current variable values. For events, we can dynamically subscribe and unsubscribe to events with event handler methods.

Let’s assume we want to raise an event in the Adder class if the sum of the two numbers in Add() is a multiple of five (5). We can define an event based on the delegate. This event will be used to raise a notification to run event handlers assigned to it.

NOTE: All C# events in .NET are based on delegates.

NOTE: Wherever you want to raise an event, you must also define the event.

NOTE:You must never raise (publish) an event unless at least one object is listening (subscribing) to the event. In other words, the event must not equal null.

NOTE: A Microsoft Best Practice: All events should be defined starting with the word “On”.

This code only raises the C# event if there is any code subscribing to it. Let’s modify the code by removing the simple delegate and have it subscribe to the event.

When run, here is the result:

Result after running the modified code to raise the C# event.

This code creates a new instance of the dgEventRaiser delegate that points to the new method called a_MultipleOfFiveReached. The += operator is used to protect other methods that may have already subscribed to the event.

This code works fine but the code in the Adder class is more complex than it needs to be. Microsoft has included two (2) primary delegates that we can use when defining events. These delegates are used everywhere in the framework and can be easier to use because of their consistent pattern.

Here are the two built-in delegates:

The first delegate is used simply to raise a notification, an event signifying that something happened. The second delegate allows you to return one or more values to the event handler method. It requires you to create an instance of a class that derives from the EventArgs class.

To modify our code to use the first built-in delegate, we can delete our delegate and change our C# event to use the EventHandler delegate. When we raise the event, we must follow along with the delegate definition and pass in the required parameter values. Note how we pass our current instance of adder for the first parameter (sender) and since we are not passing back any event arguments, we use EventArgs.Empty for “e”.

We also had to change our event handler method to follow the pattern of the delegate with (object sender, EventArgs e).

In order to use the other delegate and pass the grand total back to the event hander method, we first need to define a custom class called MultipleOfFiveEventArgs for passing back a custom value, such as Total. It must inherit from the EventArgs class.

Then we will need to define our event to use the other generic delegate which includes the custom EventArgs type, MultipleOfFiveEventArgs. We must also change how we raise the event. Finally, we change the event handler method to match the delegate.

Here is the complete code:

Conclusion

I hope this C# events tutorial has been helpful for you in learning delegates and events. Best wishes and happy programming!

GET TO KNOW US

Davin Mickelson

Intertech Instructor

Davin is a lead instructor at Intertech and author of several blog posts on topics that include everything you would ever need to know about Microsoft software technologies.

 

“Whether you need help implementing Agile or need to boost your capabilities with a team of software developers that have proven expertise in design and development, no matter the technology, our proven consulting services can help you succeed the first time.”

 

Consulting Services

Consider introducing Intertech’s experience into your project and you will realize a higher degree of success around project goals, deliverables, timelines, and budgets.

Training Services

Consider Intertech for your companies training needs! A primary provider of training for fortune 5 to 5000 companies, Intertech brings a (1) proven resource that (2) knows how to plug into your system in a way that (3) accents your internal university system and makes you look great.

Custom Application Development For Line-of-Business Needs

 

Understanding your industry is one thing. Understanding the technology you are currently using and being able to look to the future and suggest the best pathway forward is another. Add the unique benefit of being tied to a training division that keeps everyone on your team up-to-date, and you get a blend of exceptional knowledge that plugs in, does what you need, and leaves your business stronger.

When you read studies that tell you that 75% of projects are doomed from the beginning, it has to make you wonder if you have the right team in place. Consider letting our proven professionals take a look at your project. They’ve seen what can go wrong and know how to avoid the costly errors. At Intertech we ask the right questions and we tell you the right answers. From design to rollout, Intertech takes the worry out of custom software development. 

We Bring You…

Team-Complete™ Development

Intertech’s Team-Complete™ development means senior consultants dive deep into your project. From analyzing your objectives and your CIO’s vision for the future to choosing the correct pathway for your company and customers, we make sure all the right people are seated at the table to assure success.

Balanced-Cost Account Management

Intertech specializes in top-tier developers, but not everyone on a project needs to be a lead consultant. That’s where Intertech’s Momentum-Based Budgeting comes in. Providing a balanced approach, Intertech always offers you a completely integrated solution that meets the requirements and leaves your team stronger.

Soft-Skills For A Winning Experience

Sometimes the most critical person in the room is the one with a calm voice and the right words. Bringing a development team together or presenting a difficult concept for stakeholders to understand can make all the difference in success or failure. Intertech consultants are at the top of their field. They navigate challenging decisions, guide with a confident voice, and know when to get out of the way.

Tell us how we can help!

Intertech takes the worry out of custom software development.

More Information To Consider

MICROSOFT POST

Cloud graphic image 1

Xamarin – What Is It? And Creating A Blank App!

QUESTIONS TO ASK

Cloud graphic image 2

Custom Software Development And Is It Time To Consider Legacy Modernization?

We Bring Our Insights To Your Project!

We would like to hear from you.