EventHandler
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: