C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In C#, events are a way for a class (publisher) to notify other classes or objects (subscribers) that something has happened without being tightly coupled. Events use the publisher-subscriber pattern, making it easier to create and maintain applications with loosely coupled components. In this tutorial, we'll cover how to define, raise, and subscribe to events in C#.
A delegate is a reference type that holds a reference to a method with a specific signature. Events use delegates to define the signature of the methods that will handle the event. To define a delegate, use the delegate
keyword followed by the method signature:
public delegate void StockPriceChangedHandler(decimal oldPrice, decimal newPrice);
In this example, we define a delegate called StockPriceChangedHandler
that represents a method with two decimal parameters (oldPrice and newPrice).
To define an event, use the event
keyword followed by the delegate type and the event name:
public class Stock { public event StockPriceChangedHandler PriceChanged; private decimal _price; public decimal Price { get { return _price; } set { if (_price == value) return; decimal oldPrice = _price; _price = value; OnPriceChanged(oldPrice, _price); } } protected virtual void OnPriceChanged(decimal oldPrice, decimal newPrice) { PriceChanged?.Invoke(oldPrice, newPrice); } }
In this example, we define a Stock
class with a Price
property and a PriceChanged
event. When the Price
property is set to a new value, we call the OnPriceChanged()
method, which raises the PriceChanged
event by invoking the delegate (if it's not null).
To subscribe to an event, create a method with the same signature as the delegate and use the +=
operator to add it to the event:
public class StockMonitor { public StockMonitor(Stock stock) { stock.PriceChanged += OnStockPriceChanged; } private void OnStockPriceChanged(decimal oldPrice, decimal newPrice) { Console.WriteLine($"Stock price changed: {oldPrice} -> {newPrice}"); } }
In this example, we define a StockMonitor
class with a constructor that takes a Stock
object. In the constructor, we subscribe the OnStockPriceChanged()
method to the PriceChanged
event of the Stock
object.
Here's an example demonstrating how to use events to create a simple stock price monitoring application:
using System; namespace EventsTutorial { class Program { static void Main(string[] args) { Stock stock = new Stock { Price = 100m }; StockMonitor monitor = new StockMonitor(stock); stock.Price = 110m; // Stock price changed: 100 -> 110 stock.Price = 90m; // Stock price changed: 110 -> 90 } } }
In this example, we create a Stock
object, a StockMonitor
object that subscribes to the PriceChanged
event, and update the stock price. When the stock price changes, the StockMonitor
object is notified, and the OnStockPriceChanged()
method is called.
How to use events in C#:
using System; // Publisher class class Publisher { public event EventHandler SomethingHappened; public void DoSomething() { // Do something important OnSomethingHappened(); } protected virtual void OnSomethingHappened() { SomethingHappened?.Invoke(this, EventArgs.Empty); } } // Subscriber class class Subscriber { public void HandleEvent(object sender, EventArgs e) { Console.WriteLine("Something happened!"); } } class Program { static void Main() { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(); // Subscribe to the event publisher.SomethingHappened += subscriber.HandleEvent; // Trigger the event publisher.DoSomething(); } }
C# custom events example:
using System; // Custom event arguments public class CustomEventArgs : EventArgs { public string CustomData { get; set; } } // Publisher class with custom event class Publisher { public event EventHandler<CustomEventArgs> SomethingCustomHappened; public void DoSomething() { CustomEventArgs args = new CustomEventArgs { CustomData = "Custom data" }; OnSomethingCustomHappened(args); } protected virtual void OnSomethingCustomHappened(CustomEventArgs e) { SomethingCustomHappened?.Invoke(this, e); } } // Subscriber class for custom event class Subscriber { public void HandleCustomEvent(object sender, CustomEventArgs e) { Console.WriteLine($"Something custom happened with data: {e.CustomData}"); } } class Program { static void Main() { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(); // Subscribe to the custom event publisher.SomethingCustomHappened += subscriber.HandleCustomEvent; // Trigger the custom event publisher.DoSomething(); } }