public delegate void EventHandler(object sender, EventArgs e); public class Button { public event EventHandler Click; public void OnClick(EventArgs e) { Click?.Invoke(this, e); } } public class Program { static void Main() { var button = new Button(); button.Click += (sender, e) => Console.WriteLine("Button clicked!"); button.OnClick(EventArgs.Empty); } }
public delegate T TransformerThis example demonstrates how to use C# delegate to implement callback methods. The `Transformer(T input); public static class EnumerableExtensions { public static IEnumerable Map (this IEnumerable source, Transformer transformer) { foreach (var item in source) { yield return transformer(item); } } } public class Program { static void Main() { var numbers = Enumerable.Range(1, 5); var squares = numbers.Map(x => x * x); foreach (var square in squares) { Console.WriteLine(square); } } }