✅ Markdown with colorful code snippets
Real-World C# Delegate Example: Event Handling in Action
Delegates are one of the most powerful features in C#. They allow methods to be passed around like variables, and are the foundation for events and callbacks.
Let’s look at a real-world example — handling a button click in a Windows Forms application.
What is a Delegate?
A delegate is a type that represents references to methods with a specific parameter list and return type.
public delegate void ClickHandler(string message);
Real-World Example: Button Click Event
Here’s a scenario: you’re building a simple desktop app with a button. When the button is clicked, you want to log a message.
Step 1: Define the Delegate
public delegate void ButtonClickHandler(string message);
Step 2: Create a Class That Uses It
public class Button
{
public ButtonClickHandler OnClick;
public void Click()
{
OnClick?.Invoke("Button was clicked!");
}
}
Step 3: Use It in Your App
class Program
{
static void Main()
{
var button = new Button();
button.OnClick = LogMessage;
button.Click();
}
static void LogMessage(string msg)
{
Console.WriteLine(msg);
}
}
Why Is This Useful?
- Allows loose coupling — your
Buttonclass doesn't need to know whatLogMessagedoes. - Encourages reusability and testability.
- Forms the basis of event-driven programming in .NET.
Bonus: Use with event Keyword
To follow proper event conventions, use event:
public event ButtonClickHandler OnClick;
This prevents external classes from invoking the delegate directly.
Final Thoughts
Delegates are a core part of C#. Whether you're handling button clicks or building custom event systems, understanding how they work can level up your .NET skills.
Stay tuned for more C# tips and patterns. Happy coding!