C# Delegate Operator with Example – A Fun and Easy Guide
Ever felt like your code is getting messy with too many methods? Or maybe you wish you could pass a method like a variable? Well, my friend, say hello to the Delegate Operator in C#! 🎉
By the end of this lesson, you’ll understand delegates, write cleaner code, and see a real-world example to make things super clear. Let’s go! 😃
What is a Delegate?
A delegate is like a function pointer. Think of it as a variable that can hold a method. Instead of calling a method directly, you can store it in a delegate and call it whenever needed.
Here’s a simple example:
using System;
class Program
{
delegate void Greet(string name); // Declaring a delegate
static void SayHello(string name)
{
Console.WriteLine($"Hello, {name}! 👋");
}
static void Main()
{
Greet greetDelegate = SayHello; // Assign method to delegate
greetDelegate("Steven"); // Call method using delegate
}
}
Output:
Hello, Steven! 👋
Breaking Down the Code
delegate void Greet(string name);→ Declares a delegate that holds a method with astringparameter andvoidreturn.static void SayHello(string name)→ A simple method to print a greeting.Greet greetDelegate = SayHello;→ AssignsSayHellomethod to the delegate.greetDelegate("Steven");→ Calls the method using the delegate.
See? Instead of calling SayHello directly, we stored it in a delegate and called it dynamically! Super cool, right? 😎
Why Use Delegates?
✔️ Flexibility – Pass methods as parameters.
✔️ Cleaner Code – Reduce repetitive method calls.
✔️ Event Handling – Used in event-driven programming.
✔️ Reusability – Makes code modular and easy to maintain.
Real-World Example – Sending Notifications
Imagine you’re building a notification system. You want the flexibility to send email, SMS, or push notifications based on user choice. Instead of writing separate calls for each, let’s use a delegate!
Here’s the code:
using System;
class Program
{
// Declare delegate
delegate void NotifyUser(string message);
static void SendEmail(string message)
{
Console.WriteLine($"📧 Email sent: {message}");
}
static void SendSMS(string message)
{
Console.WriteLine($"📱 SMS sent: {message}");
}
static void Main()
{
NotifyUser notify;
// User chooses email
notify = SendEmail;
notify("Your order has been shipped!");
// User chooses SMS
notify = SendSMS;
notify("Your OTP is 123456.");
}
}
Output:
📧 Email sent: Your order has been shipped!
📱 SMS sent: Your OTP is 123456.
Code Explanation
delegate void NotifyUser(string message);→ Creates a delegate that holds a method with astringparameter.notify = SendEmail;→ AssignsSendEmailmethod tonotify.notify("Your order has been shipped!");→ CallsSendEmail.notify = SendSMS;→ Switches toSendSMS.notify("Your OTP is 123456.");→ CallsSendSMS.
Boom! 💥 No need for multiple if-else conditions! Just assign a different method to the delegate and call it. Simple and powerful! 🚀
Wrapping It Up
Today, we explored C# Delegate Operator with example and saw how it makes code more flexible and reusable. We also built a real-world notification system using delegates.
So, what do you think? 🤔 Have you tried using delegates before? If not, now’s the time! If you get stuck, don’t panic. Just ask, and I’ll help! 😊
Next What?
Awesome job! 🎉 You just unlocked the power of delegates. What’s next? In the next lesson, you’ll learn about the Await Operator – a game-changer for handling asynchronous tasks.
Stay curious, my friend! 🚀 See you in the next lesson! 😃
