Delegates in C# – A Beginner's Guide with Examples
🚀 Introduction to Delegates in C#
Hey there, C# learner! Ever wondered how you can pass methods as parameters in C#? Well, that’s where Delegates in C# come to the rescue. 🎉
Think of delegates as function pointers, but much cooler and safer! They allow you to reference a method and call it later, just like giving someone your phone number so they can call you when needed. Sounds interesting, right? Let’s break it down step by step.
📚 What You Are Going to Learn in This Lesson
✔️ What Delegates in C# are and why they are useful.
✔️ How to declare and use delegates.
✔️ Different types of delegates (Single, Multi-cast, Built-in).
✔️ A real-world example of delegates.
✔️ Best practices and common mistakes.
Sounds exciting? Let’s get started! 🚀
🔍 Why Are Delegates in C# Important?
Imagine you go to a restaurant and place an order. The restaurant has different chefs for different dishes:
➡️ Chef A cooks pasta 🍝
➡️ Chef B makes pizza 🍕
➡️ Chef C prepares salads 🥗
The waiter (delegate) takes your order and sends it to the right chef without knowing who exactly will cook it.
💡 How It Relates to Delegates in C#?
- The delegate acts as a middleman (waiter).
- It calls the correct method dynamically (sends the order to the right chef).
- You get your food without worrying about who cooked it!
This is exactly how Delegates in C# work—methods (chefs) are assigned dynamically, making the system flexible and reusable! 🚀
Similarly, Delegates in C# allow methods to be passed around like variables, making your code flexible, reusable, and modular.
👉 They are widely used in event handling, callbacks, and designing extensible applications.
📝 Syntax of Delegates in C#
Here’s the basic syntax for declaring and using a delegate:
// 1️⃣ Declare a delegate (It holds a method reference)
delegate void MyDelegate(string message);
// 2️⃣ Create a method matching delegate signature
void SayHello(string msg) {
Console.WriteLine("Hello, " + msg);
}
// 3️⃣ Use the delegate to call the method
MyDelegate del = new MyDelegate(SayHello);
del("C# Learner");
🛠 Explanation:
delegate void MyDelegate(string message);
→ Declares a delegate that holds a method with astring
parameter.void SayHello(string msg)
→ A method that prints a greeting.MyDelegate del = new MyDelegate(SayHello);
→ AssignsSayHello
todel
.del("C# Learner");
→ Calls theSayHello
method using the delegate.
📌 Output:
Hello, C# Learner
Simple, right? Now, let’s look at different ways to use Delegates in C#.
🎯 Single-Cast Delegate Example
A single-cast delegate holds a reference to one method at a time.
using System;
delegate void Greet(string name);
class Program {
static void SayHi(string name) {
Console.WriteLine("Hi, " + name);
}
static void Main() {
Greet greet = SayHi;
greet("John");
}
}
📝 Step-by-Step Explanation:
1️⃣ Declare a Delegate:
delegate void Greet(string name);
- ➡️ This defines a delegate named
Greet
that holds a method with a string parameter and returnsvoid
. - ➡️ Think of it as a function pointer that can store references to methods with the same signature.
2️⃣ Create a Method That Matches the Delegate Signature:
static void SayHi(string name) {
Console.WriteLine("Hi, " + name);
}
- ➡️ This method takes a string (
name
) and prints"Hi, <name>"
. - ➡️ It matches the delegate’s signature, so it can be assigned to the delegate.
3️⃣ Assign the Method to the Delegate:
Greet greet = SayHi;
- ➡️ Here, we create a
Greet
delegate instance namedgreet
. - ➡️ We assign the
SayHi
method to it. - ➡️ Now,
greet
acts like a function variable that can callSayHi()
.
4️⃣ Call the Delegate:
greet("John");
- ➡️ Instead of calling
SayHi("John")
directly, we callgreet("John")
. - ➡️ The delegate automatically calls
SayHi
, passing"John"
as the argument.
📌 Output:
Hi, John
🔄 Multi-Cast Delegate Example
A multi-cast delegate holds references to multiple methods and calls them all.
using System;
delegate void Notify();
class Program {
static void ShowMessage() {
Console.WriteLine("Notification: You have a new message!");
}
static void ShowAlert() {
Console.WriteLine("Alert: Check your inbox.");
}
static void Main() {
Notify notify = ShowMessage;
notify += ShowAlert; // Adding another method
notify();
}
}
📝 Step-by-Step Explanation:
1️⃣ Declare a Delegate:
delegate void Notify();
- ➡️ Defines a delegate
Notify
that can store methods with no parameters andvoid
return type.
2️⃣ Create the First Method:
static void ShowMessage() {
Console.WriteLine("Notification: You have a new message!");
}
- ➡️ Prints a notification message.
- ➡️ Matches the
Notify
delegate signature.
3️⃣ Create the Second Method:
static void ShowAlert() {
Console.WriteLine("Alert: Check your inbox.");
}
- ➡️ Prints an alert message.
- ➡️ Matches the
Notify
delegate signature.
4️⃣ Assign the First Method to the Delegate:
Notify notify = ShowMessage;
- ➡️
notify
stores the reference toShowMessage()
.
5️⃣ Add the Second Method (Multi-Casting):
notify += ShowAlert;
- ➡️
notify
now holds two methods:- ✅
ShowMessage()
- ✅
ShowAlert()
- ✅
- ➡️ Both methods will execute when
notify()
is called.
6️⃣ Invoke the Delegate:
notify();
- ➡️ Calls all methods stored in
notify
.
📌 Output:
Notification: You have a new message!
Alert: Check your inbox.
🔄 Built-in Delegates: Action, Func, and Predicate
C# provides built-in delegates to make life easier.
➡️ Action – Used when a method returns void
.
➡️ Func – Used when a method returns a value.
➡️ Predicate – Used when a method returns a Boolean (true
or false
).
Example using Action:
using System;
class Program {
static void PrintMessage(string msg) {
Console.WriteLine(msg);
}
static void Main() {
Action<string> action = PrintMessage;
action("Hello from Action delegate!");
}
}
📝 Step-by-Step Explanation:
1️⃣ Creates an Action
delegate:
Action<string> action = PrintMessage;
- ➡️
Action<string>
is a built-in delegate that can store methods with onestring
parameter and no return value (void
). - ➡️
PrintMessage
method is assigned to the delegateaction
. - ➡️ Now,
action
behaves like a function pointer toPrintMessage
.
2️⃣ Invokes the delegate:
action("Hello from Action delegate!");
- ➡️ Calls
PrintMessage("Hello from Action delegate!")
. - ➡️ Prints the message on the console.
📌 Output:
Hello from Action delegate!
🔥 Why Use Action<T>
?
✔ Avoids creating custom delegates – Makes code cleaner.
✔ More flexible – Can store any method with matching signature.
✔ Improves readability – No need for extra delegate declarations.
🌍 Real-World Example: Payment Processing System
Imagine an online payment system that supports different payment methods like Credit Card, PayPal, and Crypto.
Using Delegates in C#, we can dynamically select a payment method.
using System;
delegate void PaymentMethod(double amount);
class Program {
static void PayByCreditCard(double amount) {
Console.WriteLine($"Paid ${amount} using Credit Card.");
}
static void PayByPayPal(double amount) {
Console.WriteLine($"Paid ${amount} using PayPal.");
}
static void Main() {
PaymentMethod payment;
payment = PayByCreditCard;
payment(100.50);
payment = PayByPayPal;
payment(75.25);
}
}
📌 Output:
Paid $100.50 using Credit Card.
Paid $75.25 using PayPal.
🔥 Why is this useful?
➡️ Makes the system flexible.
➡️ Easily add new payment methods without changing existing code.
➡️ Helps in implementing strategy patterns.
🎯 Common Mistakes to Avoid
❌ Forgetting to initialize the delegate before calling it.
❌ Not matching the delegate signature with the method signature.
❌ Forgetting to unsubscribe from multi-cast delegates when no longer needed.
🎉 Conclusion
Wow! You made it through Delegates in C#. You now know:
✔️ How to declare and use delegates.
✔️ Different types of delegates (Single-cast, Multi-cast, Built-in).
✔️ A real-world example of how to use them.
Delegates in C# are powerful and make your code flexible, reusable, and modular. Keep practicing, and soon, you’ll be using them like a pro! 🚀
👉 Next What?
In the next chapter, we’ll learn how to create and use delegates in detail. Stay tuned, and happy coding! 🎯💻