Delegates and Events in C# - Practical Examples
Quick Answer
Delegates in C# are type-safe function pointers that allow methods to be passed as parameters. Events use delegates to enable a publisher-subscriber model, facilitating communication between objects. Practical examples include button click handlers and custom event notifications, essential for responsive and modular applications.
Learning Objectives
- Explain the purpose of Practical Examples in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Practical Examples.
- Apply Practical Examples in a simple real-world scenario or practice task.
Introduction to Delegates and Events
Delegates and events are fundamental concepts in C# that enable event-driven programming.
Delegates act as type-safe pointers to methods, while events provide a way for objects to notify other objects when something happens.
Events and delegates enable loose coupling and flexible communication between components.
Understanding Delegates
A delegate is a type that represents references to methods with a specific parameter list and return type.
Delegates allow methods to be passed as parameters, stored, and invoked dynamically.
- Type-safe method references
- Can reference static or instance methods
- Support multicast invocation
Simple Delegate Example
Here is a simple example demonstrating how to declare and use a delegate.
Working with Events
Events are built on top of delegates and provide a way to subscribe and respond to notifications.
They follow the publisher-subscriber pattern, where the publisher raises events and subscribers handle them.
- Events restrict delegate invocation to the declaring class
- Subscribers add or remove event handlers
- Commonly used in UI programming and asynchronous operations
Basic Event Example
This example shows how to declare an event and subscribe to it.
Practical Examples of Delegates and Events
Let's explore practical scenarios where delegates and events are used effectively.
- Button click event handling in GUI applications
- Custom event notifications in business logic
- Logging and callback mechanisms
Example: Button Click Event Handler
In this example, a button click event is handled using delegates and events.
Example: Custom Event for Data Processing
This example demonstrates raising a custom event when data processing completes.
Practical Example
This example declares a delegate named Notify that points to the ShowMessage method. The delegate is invoked to print a message.
This example shows a Publisher class raising an event and a Subscriber class handling it by subscribing to the event.
This example simulates a button click event where the Click event is raised and handled by a subscribed method.
This example defines a custom event with event data. The DataProcessor raises the event after processing, and the subscriber handles it.
Examples
public delegate void Notify(string message);
class Program
{
static void Main()
{
Notify notifyDelegate = ShowMessage;
notifyDelegate("Hello from delegate!");
}
static void ShowMessage(string message)
{
Console.WriteLine(message);
}
}This example declares a delegate named Notify that points to the ShowMessage method. The delegate is invoked to print a message.
using System;
class Publisher
{
public event EventHandler OnChange;
public void RaiseEvent()
{
OnChange?.Invoke(this, EventArgs.Empty);
}
}
class Subscriber
{
public void Subscribe(Publisher pub)
{
pub.OnChange += HandleEvent;
}
private void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("Event received.");
}
}
class Program
{
static void Main()
{
Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
sub.Subscribe(pub);
pub.RaiseEvent();
}
}This example shows a Publisher class raising an event and a Subscriber class handling it by subscribing to the event.
using System;
class Button
{
public event EventHandler Click;
public void OnClick()
{
Click?.Invoke(this, EventArgs.Empty);
}
}
class Program
{
static void Main()
{
Button button = new Button();
button.Click += Button_Click;
button.OnClick();
}
private static void Button_Click(object sender, EventArgs e)
{
Console.WriteLine("Button was clicked!");
}
}This example simulates a button click event where the Click event is raised and handled by a subscribed method.
using System;
class DataProcessor
{
public event EventHandler<DataEventArgs> DataProcessed;
public void ProcessData()
{
// Simulate data processing
System.Threading.Thread.Sleep(1000);
OnDataProcessed(new DataEventArgs("Data processed successfully."));
}
protected virtual void OnDataProcessed(DataEventArgs e)
{
DataProcessed?.Invoke(this, e);
}
}
class DataEventArgs : EventArgs
{
public string Message { get; }
public DataEventArgs(string message) { Message = message; }
}
class Program
{
static void Main()
{
DataProcessor processor = new DataProcessor();
processor.DataProcessed += Processor_DataProcessed;
processor.ProcessData();
}
private static void Processor_DataProcessed(object sender, DataEventArgs e)
{
Console.WriteLine(e.Message);
}
}Best Practices
- Use delegates and events to decouple components and promote modular design.
- Always check for null before invoking events to avoid exceptions.
- Use EventHandler<T> for events with custom data to follow .NET conventions.
- Unsubscribe from events when no longer needed to prevent memory leaks.
- Keep event handlers short and efficient to maintain responsiveness.
Common Mistakes
- Invoking events without null checks causing NullReferenceException.
- Not unsubscribing event handlers leading to memory leaks.
- Using delegates directly instead of events for public notifications.
- Modifying event invocation list from outside the declaring class.
- Blocking the main thread with long-running event handlers.
Hands-on Exercise
Create a Custom Event
Implement a class that raises a custom event when a threshold is reached. Write a subscriber that handles this event and prints a message.
Expected output: A message printed when the threshold event is raised.
Hint: Define a delegate or use EventHandler<T>, raise the event when the condition is met, and subscribe to it in another class.
Implement Multicast Delegate
Create a delegate that points to multiple methods and invoke it to see all methods executed.
Expected output: All methods assigned to the delegate are called in order.
Hint: Use the += operator to add methods to the delegate invocation list.
Interview Questions
What is a delegate in C#?
InterviewA delegate is a type-safe object that points to a method or methods with a specific signature, allowing methods to be passed as parameters or assigned to variables.
How do events differ from delegates?
InterviewEvents are built on delegates but restrict the invocation of the delegate to the declaring class, providing a controlled way for subscribers to register handlers without invoking the event themselves.
Why should you unsubscribe from events?
InterviewUnsubscribing prevents memory leaks by allowing the garbage collector to reclaim objects that are no longer needed but still referenced by event handlers.
MCQ Quiz
1. What is the best first step when learning Practical Examples?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Practical Examples?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. Delegates in C# are type-safe function pointers that allow methods to be passed as parameters.
B. Practical Examples never needs examples
C. Practical Examples is unrelated to practical work
D. Practical Examples should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Delegates in C# are type-safe function pointers that allow methods to be passed as parameters.
- Events use delegates to enable a publisher-subscriber model, facilitating communication between objects.
- Practical examples include button click handlers and custom event notifications, essential for responsive and modular applications.
- Delegates and events are fundamental concepts in C# that enable event-driven programming.
- Delegates act as type-safe pointers to methods, while events provide a way for objects to notify other objects when something happens.
Summary
Delegates and events are powerful features in C# that enable flexible and decoupled event-driven programming.
Delegates provide type-safe references to methods, while events allow safe subscription and notification mechanisms.
Understanding and applying these concepts with best practices leads to maintainable and responsive applications.
Frequently Asked Questions
Can a delegate reference multiple methods?
Yes, delegates in C# can be multicast, meaning they can reference and invoke multiple methods in sequence.
What is the difference between EventHandler and EventHandler<T>?
EventHandler is a delegate for events without data, while EventHandler<T> allows passing custom event data through a generic parameter.
How do you prevent memory leaks with events?
By unsubscribing event handlers when they are no longer needed, you prevent objects from being kept alive unintentionally.
What is Practical Examples?
Delegates in C# are type-safe function pointers that allow methods to be passed as parameters.
Why is Practical Examples important?
Events use delegates to enable a publisher-subscriber model, facilitating communication between objects.
How should I practice Practical Examples?
Practical examples include button click handlers and custom event notifications, essential for responsive and modular applications.

