c# delegates explained code example

Example 1: delegates in c#

//start with Delegate

using System;
using System.IO;

class Delegate
{
  //create delegate using delegate keyword
  public delegate void HelloMethod(string str);
  //Remove delegate Keyword it will be normal method declaration
  
  public static void Main(String [] args)
  {
    //function poiting to delegate instance
     HelloMethod delegateInstance = new HelloMethod(print);
    //calling delegate which invokes function print()
    delegateInstance("Hey there! Iam delegate method");
  }
  
  public static void print(string delegateStr)
  {
    Console.WriteLine(delegateStr);
  }
}
//Information on delegate

//Delegate is a type safe function pointer which means can point a function to 
//the delegate when delegate get invokes function automatically invokes since 
//function is pointed to the delegate

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: what are delegates and how to use them c#

public delegate void MyDelegate(string text);

Example 4: delegate declaration in c#

public delegate int PerformCalculation(int x, int y);

Example 5: what are delegates and how to use them c#

delegate result-type identifier ([parameters])

Example 6: what are delegates and how to use them c#

MyDelegate d = new MyDelegate(ShowText);