Delegates in C#
Delegates in C#
In C#, delegates are types that hold references to
methods with a specific signature. They allow methods to be passed around as
parameters, or even assigned to variables. Essentially, a delegate is like a pointer
to a method that has the same signature (same return type and parameters). This
makes delegates useful for event-driven programming, callbacks, and
implementing the Observer pattern.
Delegates are often used in scenarios like:
- Event
handling (as with GUI buttons)
- Callbacks
- Passing
methods as parameters
Delegate Definition
A delegate defines the method signature — that is, the
return type and the parameters that the method accepts. It acts as a contract,
meaning only methods that match this signature can be assigned to the delegate.
Syntax for a delegate declaration:
public delegate void ButtonClickHandler(string message);
Here, ButtonClickHandler is a delegate that expects methods
that return void and take a single string parameter.
Using Delegates with Events (Button Click Example)
Let's look at a simple example where delegates help handle
button clicks with different actions:
- Define
a Delegate Type: We define a delegate that matches the signature of
the method that will handle the button click.
- Define
Methods for Actions: We create methods that perform different actions
on button clicks.
- Assign
Methods to Delegate Instances: We create delegate instances and assign
different methods (actions) to them.
- Hook
Up the Delegate to a Button's Click Event: The delegate can be invoked
when the button is clicked.
Here’s a complete example:
Example Code:
using System;
public class Button
{
// Delegate
declaration
public delegate
void ButtonClickHandler(string message);
// Event based on
the delegate
public event
ButtonClickHandler OnClick;
// Method to
simulate a button click
public void
Click(string message)
{
// If any
methods are subscribed to the OnClick event, invoke them
OnClick?.Invoke(message);
}
}
public class Program
{
// Different
actions to take when the button is clicked
public static void
ActionOne(string message)
{
Console.WriteLine("Action One: " + message);
}
public static void
ActionTwo(string message)
{
Console.WriteLine("Action Two: " + message);
}
public static void
Main(string[] args)
{
// Create an
instance of Button
Button
myButton = new Button();
// Create
delegate instances and hook methods to the OnClick event
Button.ButtonClickHandler
action1 = new Button.ButtonClickHandler(ActionOne);
Button.ButtonClickHandler action2 = new
Button.ButtonClickHandler(ActionTwo);
// Subscribe
methods to the button click event
myButton.OnClick += action1;
myButton.OnClick += action2;
// Simulate a
button click
myButton.Click("Button clicked!");
// Output:
// Action One:
Button clicked!
// Action Two:
Button clicked!
}
}
Explanation of the Code:
- Button
Class:
- The
Button class contains a delegate ButtonClickHandler, which defines the
method signature (a method that takes a string parameter and returns void).
- It
also defines an event OnClick, which uses this delegate.
- The
Click method simulates a button click and invokes all methods subscribed
to the OnClick event.
- Program
Class:
- ActionOne
and ActionTwo are methods that match the delegate signature.
- In Main,
instances of the ButtonClickHandler delegate are created and hooked up to
the OnClick event of the myButton object.
- When
the Click method is invoked, all subscribed methods (ActionOne and ActionTwo)
are called with the provided message.
Why Use Delegates Here?
- Decoupling:
The button’s click event can trigger different actions without having the
button know about the specific methods. It just relies on the delegate to
call any methods subscribed to it.
- Flexibility:
New actions can be added to the button’s click event without modifying the
button code. Simply subscribe new methods to the delegate.
- Event
Handling: Delegates make event-driven programming more organized. In
GUI frameworks like Windows Forms or WPF, delegates are frequently used to
handle events such as button clicks.
Multi-casting with Delegates:
Notice how both ActionOne and ActionTwo are invoked when the
button is clicked. This is because delegates in C# can multicast,
meaning multiple methods can be attached to the same delegate. When the
delegate is invoked, all methods in the invocation list are called in the order
they were added.
Conclusion:
Delegates in C# are powerful tools for event-driven
programming, as they allow methods to be passed around as first-class objects.
In the case of the button click example, delegates allow different actions to
be performed dynamically in response to the same event, without tightly
coupling the event source (the button) to the action handlers.
Comments
Post a Comment