delegates in c# 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
public delegate double MyDelegateType(double x);
public double Consummer(double x, MyDelegateType f){
return f(x);
}
public double MyFunctionMethod(double x){
return x;
}
public void Client(){
double result = Consummer(1.234, x => x * 456.1234);
double secondResult = Consummer(2.345, MyFunctionMethod);
}
Example 3: 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 4: delegate function c#
public delegate void Del(string message);
public static void DelegateMethod(string message)
{
Console.WriteLine(message);
}
Del hadler = DelegateMethod;
hadler("Hello World");
Example 5: what are delegates and how to use them c#
public delegate void MyDelegate(string text);
Example 6: delegate declaration in c#
public delegate int PerformCalculation(int x, int y);