← Back to C# Course | Chapter 12: Delegates & Events | Lesson 6 of 6

EventHandler

EventHandler is the standard shape for events in .NET, like a standard form everyone fills in the same way. It carries who sent the event and any extra details.

In this page:

  1. EventHandler
Syntax
csharp
class DataEventArgs : EventArgs
{
    public type Data;
}

public event EventHandler<DataEventArgs> EventName;

EventName?.Invoke(this, new DataEventArgs { Data = value });

void Handler(object sender, DataEventArgs e) { }

EventHandler

EventHandler and EventHandler<TEventArgs> are the standard .NET delegate types for events, following the convention of a sender object and an EventArgs-derived parameter.

Using them keeps your events consistent with the rest of the .NET ecosystem. TEventArgs typically carries extra data about what happened.

Note: Custom event data classes should inherit from EventArgs, by convention named ending in "EventArgs".

Example: EventHandler

markup
using System;

class PriceChangedEventArgs : EventArgs
{
    public decimal NewPrice;
}

class Stock
{
    public event EventHandler<PriceChangedEventArgs> PriceChanged;

    public void UpdatePrice(decimal price)
    {
        PriceChanged?.Invoke(this, new PriceChangedEventArgs { NewPrice = price });
    }
}

class Program
{
    static void Main(string[] args)
    {
        Stock stock = new Stock();
        stock.PriceChanged += (sender, e) => Console.WriteLine($"New price: {e.NewPrice}");

        stock.UpdatePrice(101.5m);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Raising the event with PriceChanged(this, args) when nobody has subscribed, which throws a NullReferenceException; use PriceChanged?.Invoke(this, args).
  2. Trying to assign or raise the event from outside its class with stock.PriceChanged = handler;, when outside code can only use += and -=.
  3. Writing a handler with the wrong signature, since an EventHandler<T> method must take (object sender, T e), and forgetting to subscribe with += so nothing happens.
Chapter Summary
  • Delegates hold references to methods, and multicast delegates can call several methods.
  • Lambda expressions and Func, Action, and Predicate write short delegates.
  • Events and EventHandler let objects notify others when something happens.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.