Delegates and Events - potatoscript/csharp GitHub Wiki
๐ฅ Delegates and Events in C# ๐ฅ
๐ฏ What Are Delegates in C#?
A delegate in C# is like a remote control that tells a TV what to do. ๐ฎ๐บ You press a button, and the TV knows whether to change the channel, adjust the volume, or turn off.
In C# terms:
- A delegate is a pointer to a method.
- It allows you to call a method without knowing its exact name.
- Delegates can hold references to one or more methods and call them dynamically.
๐ฅ Why Use Delegates?
Imagine youโre running a potato warehouse. Sometimes you want to:
- ๐ฆ Pack the potatoes.
- ๐ Ship the potatoes.
- ๐งน Clean the warehouse.
Instead of calling each method separately, you can assign them to a delegate and call them dynamically when needed.
๐ง How to Declare a Delegate
๐ฅ Step 1: Declare a Delegate
You declare a delegate like you declare a function prototype.
public delegate void PotatoAction(string message);
โ Explanation:
public delegate
โ Declares a delegate.void
โ Return type of the method it points to.PotatoAction
โ Name of the delegate.string message
โ Parameter that the delegateโs method will accept.
๐ฅ Step 2: Create Methods That Match the Delegate Signature
public class PotatoWarehouse
{
public void PackPotatoes(string message)
{
Console.WriteLine("๐ฆ Packing Potatoes: " + message);
}
public void ShipPotatoes(string message)
{
Console.WriteLine("๐ Shipping Potatoes: " + message);
}
}
โ Explanation:
PackPotatoes()
andShipPotatoes()
are two methods that match the delegateโs signature.- Both accept a
string
parameter and returnvoid
.
๐ฅ Step 3: Assign Methods to a Delegate
class Program
{
static void Main()
{
PotatoWarehouse warehouse = new PotatoWarehouse();
// Create a delegate instance
PotatoAction action;
// Assign PackPotatoes to the delegate
action = warehouse.PackPotatoes;
action("Golden Potatoes");
// Change delegate to ShipPotatoes
action = warehouse.ShipPotatoes;
action("Purple Potatoes");
}
}
โ Explanation:
action = warehouse.PackPotatoes
โ Assigns thePackPotatoes
method to the delegate.action("Golden Potatoes")
โ Calls thePackPotatoes()
method.action = warehouse.ShipPotatoes
โ Reassigns the delegate toShipPotatoes
.
๐ Output:
๐ฆ Packing Potatoes: Golden Potatoes
๐ Shipping Potatoes: Purple Potatoes
๐ Multicast Delegates
A multicast delegate is like pressing multiple buttons on the remote control ๐ฎ. You can assign multiple methods to a single delegate, and they all get called!
๐ฅ Example: Multicast Delegate
class Program
{
static void Main()
{
PotatoWarehouse warehouse = new PotatoWarehouse();
// Create a delegate instance
PotatoAction action;
// Add multiple methods to the delegate
action = warehouse.PackPotatoes;
action += warehouse.ShipPotatoes;
// Call all methods in the delegate
action("Golden Potatoes");
}
}
โ Explanation:
action += warehouse.ShipPotatoes
โ Adds another method to the delegate.- When
action
is called, bothPackPotatoes
andShipPotatoes
are executed.
๐ Output:
๐ฆ Packing Potatoes: Golden Potatoes
๐ Shipping Potatoes: Golden Potatoes
๐ฅ Anonymous Methods and Lambda Expressions
If you donโt want to create a separate method, you can use anonymous methods or lambda expressions.
๐ฅ Anonymous Method Example:
PotatoAction action = delegate(string message)
{
Console.WriteLine("๐ Anonymous Method says: " + message);
};
action("Hello from anonymous method!");
โ Explanation:
delegate(string message)
โ Anonymous method without a name.- Can be assigned directly to the delegate.
๐ฅ Lambda Expression Example:
PotatoAction action = (message) => Console.WriteLine("๐ฅ Lambda says: " + message);
action("Hello from lambda!");
โ Explanation:
(message) => ...
โ Shorter syntax for anonymous methods.- Simplifies writing methods directly inside a delegate.
๐ Output:
๐ Anonymous Method says: Hello from anonymous method!
๐ฅ Lambda says: Hello from lambda!
๐ฏ What Are Events in C#?
An event in C# is like a potato alarm that tells you when something important happens. โฐ๐ฅ
- Events are special delegates that notify subscribers when something happens.
- Publisher โ The class that raises the event.
- Subscriber โ The class that listens and reacts to the event.
๐ง How to Declare and Use Events
๐ฅ Step 1: Define a Delegate for the Event
public delegate void PotatoProcessedEventHandler(string message);
๐ฅ Step 2: Define the Event in a Class
public class PotatoProcessor
{
// Declare an event
public event PotatoProcessedEventHandler PotatoProcessed;
public void ProcessPotatoes(string type)
{
Console.WriteLine($"๐ช Processing {type} Potatoes...");
// Raise the event after processing
if (PotatoProcessed != null)
{
PotatoProcessed.Invoke($"{type} Potatoes are ready! ๐ฅ๐");
}
}
}
โ Explanation:
PotatoProcessed
โ Event that will notify when the potatoes are processed.ProcessPotatoes()
โ Method that processes the potatoes and raises the event.
๐ฅ Step 3: Create a Subscriber to Handle the Event
public class WarehouseManager
{
public void OnPotatoProcessed(string message)
{
Console.WriteLine("๐ฃ Notification: " + message);
}
}
โ Explanation:
OnPotatoProcessed()
โ Method that reacts when the event is raised.
๐ฅ Step 4: Subscribe to the Event
class Program
{
static void Main()
{
PotatoProcessor processor = new PotatoProcessor();
WarehouseManager manager = new WarehouseManager();
// Subscribe to the event
processor.PotatoProcessed += manager.OnPotatoProcessed;
// Process the potatoes and raise the event
processor.ProcessPotatoes("Golden");
}
}
โ Explanation:
processor.PotatoProcessed += manager.OnPotatoProcessed
โ Subscribes the method to the event.ProcessPotatoes("Golden")
โ Raises the event and notifies all subscribers.
๐ Output:
๐ช Processing Golden Potatoes...
๐ฃ Notification: Golden Potatoes are ready! ๐ฅ๐
๐ฅ Multicast Events (Multiple Subscribers)
You can have multiple subscribers to the same event. Itโs like multiple warehouse managers listening for potato updates. ๐ข๐
๐ฅ Example:
class Program
{
static void Main()
{
PotatoProcessor processor = new PotatoProcessor();
WarehouseManager manager1 = new WarehouseManager();
WarehouseManager manager2 = new WarehouseManager();
// Subscribe both managers
processor.PotatoProcessed += manager1.OnPotatoProcessed;
processor.PotatoProcessed += manager2.OnPotatoProcessed;
// Process potatoes and notify both managers
processor.ProcessPotatoes("Purple");
}
}
๐ Output:
๐ช Processing Purple Potatoes...
๐ฃ Notification: Purple Potatoes are ready! ๐ฅ๐
๐ฃ Notification: Purple Potatoes are ready! ๐ฅ๐
๐ฏ Summary of Delegates and Events in C#
๐ Concept | ๐ Description |
---|---|
๐ฎ Delegates | A pointer to a method in C# |
๐บ Multicast Delegates | Call multiple methods at once |
โก Events | Notify subscribers when something happens |
๐ง Lambda Expressions | Short-hand syntax for anonymous methods |
๐ Subscriber | Listens and reacts to events |
๐ข Publisher | Raises the event to notify subscribers |