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() and ShipPotatoes() are two methods that match the delegateโ€™s signature.
  • Both accept a string parameter and return void.

๐Ÿฅ” 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 the PackPotatoes method to the delegate.
  • action("Golden Potatoes") โ€“ Calls the PackPotatoes() method.
  • action = warehouse.ShipPotatoes โ€“ Reassigns the delegate to ShipPotatoes.

๐ŸŽ 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, both PackPotatoes and ShipPotatoes 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