c# event delegate code example

Example 1: c# events

// --------------------- HOW TO CREATE EVENTS? ----------------------- //
// 1º - Main (Start the program)
// 2º - Publisher (the one that sends the event) 
// 3º - Subscriber (the one that receives the event)


// PUBLISHER:
class Publisher
{
   // 1º Create a delegate
   public delegate void MyEventHandler (object source, EventArgs args);

   // 2º Create an event based on that delegate
   public event MyEventHandler myEvents;

   // 3º Raise the event. For example, create a method that does:
   protected virtual void Method1()
   {
      if(myEvents != null)
      {
           myEvents(this, EventArgs.Empty);  // Calling the event if it points to some other method 
      }
   }

   public void Method2()
   {
      Console.WriteLine("This method is called from the Main function...");

      // Continuation of 3º step
      Method1();
     
    }
}


// SUBSCRIBER:
public class Subscriber
{
     public void Method1(object source, EventArgs e)
     {
            Console.WriteLine("The work done by the subscriber after the event was raised...");
      }
}


// MAIN:
class Program
{
   static void Main(string[] args)
   {
      var myPublisher = new Publisher();
      var mySubscriber = new Subscriber();

      // Give the Event a pointer to the function inside the class Subscriber
      myPublisher.myEvents += mySubscriber.Method1;

      myPublisher.Method2();
   }
}


// ----------- HOW TO PASS ARGUMENTS/DATA THROUGH EVENTS? ------------ //
// You have to create an EventArgs class, like:

public class MyNewEventArgs : EventArgs    // It will inherit from the EventArgs class, and you can add on top of that, some new information 
{
	public string newData {get; set;}	

}


// Then, you just need to change the following (in the code above):
// |  1º |
public delegate void EventHandler (object source, MyNewEventArgs args);  // Substitute EventArgs for MyNewEventArgs
// |  2º |
myEvents(this, new MyNewEventArgs() { newData = "Hello World!"} );  // Create an instance of the MyNewEventArgs class and pass it as a parameter of myEvents   
// |  3º |
public void Method1(object source, MyNewEventArgs e)   // Update all the other methods (substitute EventArgs for MyNewEventArgs)

// Now you can use the data inside the "e" variable on the Subscribers methods

Example 2: C# delegate

using System;

	public class CargoAircraft
    {
      	// Create a delegate type (no return no arguments)
        public delegate void CheckQuantity();
		// Create an instance of the delegate type
        public CheckQuantity ProcessQuantity;

        public void ProcessRequirements()
        {
          // Call the instance delegate
          // Will invoke all methods mapped
            ProcessQuantity();
        }
    }

    public class CargoCounter
    {
        public void CountQuantity() { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CargoAircraft cargo = new CargoAircraft();
            CargoCounter cargoCounter = new CargoCounter();
			
          	// Map a method to the created delegate
            cargo.ProcessQuantity += cargoCounter.CountQuantity;
          	
          	// Will call instance delegate invoking mapped methods
            cargo.ProcessRequirements();
        }
    }
}

Example 3: delegate function c#

// Create the Delgate method.
public delegate void Del(string message);

// Create a method for a delgate.
public static void DelegateMethod(string message)
{
  Console.WriteLine(message);
}

// Instatiate the delegate.
Del hadler = DelegateMethod;

// Call the delegate.
hadler("Hello World");

// Output
// Hello World

Example 4: delegates and events in c#

public delegate T add<T>(T param1, T param2); // generic delegate

class Program
{
    static void Main(string[] args)
    {
        add<int> sum = Sum;
        Console.WriteLine(sum(10, 20));

        add<string> con = Concat;
        Console.WriteLine(con("Hello ","World!!"));
    }

    public static int Sum(int val1, int val2)
    {
        return val1 + val2;
    }

    public static string Concat(string str1, string str2)
    {
        return str1 + str2;
    }
}