c# delegates explained code example
Example 1: delegates in c#
using System;
using System.IO;
class Delegate
{
public delegate void HelloMethod(string str);
public static void Main(String [] args)
{
HelloMethod delegateInstance = new HelloMethod(print);
delegateInstance("Hey there! Iam delegate method");
}
public static void print(string delegateStr)
{
Console.WriteLine(delegateStr);
}
}
Example 2: C# delegate
using System;
public class CargoAircraft
{
public delegate void CheckQuantity();
public CheckQuantity ProcessQuantity;
public void ProcessRequirements()
{
ProcessQuantity();
}
}
public class CargoCounter
{
public void CountQuantity() { }
}
class Program
{
static void Main(string[] args)
{
CargoAircraft cargo = new CargoAircraft();
CargoCounter cargoCounter = new CargoCounter();
cargo.ProcessQuantity += cargoCounter.CountQuantity;
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);