// Declare a singlecast delegate
delegate void MyDelegate(string message);
// Assign a method to the delegate
MyDelegate singlecastDelegate = Console.WriteLine;
// Invoke the delegate
singlecastDelegate("Hello, world!");
// Declare a multicast delegate
delegate void MultiDelegate(string message);
// Assign multiple methods to the delegate
MultiDelegate multicastDelegate = Console.WriteLine;
multicastDelegate += Console.WriteLine;
// Invoke the delegate (both methods are called)
multicastDelegate("Hello, world!");
// Using generic delegates (Func and Action)
Action<string> printMessage = Console.WriteLine;
Func<int, int, int> add = (a, b) => a + b;
printMessage("Hello, world!");
int result = add(5, 3);
Console.WriteLine("Result: " + result);
public class Example
{
// Declare an event
public event Action<string> MyEvent;
// Method to trigger the event
public void RaiseEvent(string message)
{
MyEvent?.Invoke(message);
}
}
static void Main(string[] args)
{
Example example = new Example();
// Subscribe to the event
example.MyEvent += message => Console.WriteLine("Received: " + message);
// Trigger the event
example.RaiseEvent("Hello, world!");
}