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:
Syntax
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Raising the event with
PriceChanged(this, args)when nobody has subscribed, which throws aNullReferenceException; usePriceChanged?.Invoke(this, args). - Trying to assign or raise the event from outside its class with
stock.PriceChanged = handler;, when outside code can only use+=and-=. - 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, andPredicatewrite short delegates. - Events and
EventHandlerlet objects notify others when something happens.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: