C# — Events
Basic event
public class Button
{
public event EventHandler Clicked;
public void Click()
{
Clicked?.Invoke(this, EventArgs.Empty);
}
}
var button = new Button();
button.Clicked += (sender, e) => Console.WriteLine("Clicked!");
button.Click();
Custom event args
public class OrderEventArgs : EventArgs
{
public decimal Amount { get; set; }
public string Product { get; set; }
}
public class OrderService
{
public event EventHandler<OrderEventArgs> OrderPlaced;
public void PlaceOrder(string product, decimal amount)
{
OrderPlaced?.Invoke(this, new OrderEventArgs
{
Product = product,
Amount = amount
});
}
}
Mini Practice
Write C# code that:
- Creates a basic event
- Subscribes to an event with +=
- Uses custom EventArgs
- Demonstrates event invocation
Up Next
In the next lesson, you'll learn about Attributes — metadata annotations.
Related Topics
Frequently Asked Questions about Events
What is Events in C#?
Events is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Events?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Events.
Why is Events important in C#?
Events is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.