Instantiation and invocation
Context: Create a delegate instance by referencing a method (using the method name or a lambda). Invoke it like a method.
Instantiation
Section titled “Instantiation”public delegate void Display(string text);
public static void Show(string msg) => Console.WriteLine(msg);
// Old syntax (C# 1.0)Display d1 = new Display(Show);
// Simplified syntax (C# 2.0+)Display d2 = Show;
// Using lambda (C# 3.0+)Display d3 = (msg) => Console.WriteLine(msg);Invocation
Section titled “Invocation”d2("Hello"); // invokes Showd3("World");Null check
Section titled “Null check”Always check for null before invoking a delegate.
if (d2 != null) d2("Safe");// Or using null‑conditional operatord2?.Invoke("Safe");Real-world usage example
Section titled “Real-world usage example”Button click handlers: In Windows Forms or WPF, you instantiate a delegate to wire a button click event to a method.
Example: In WinForms, button.Click += new EventHandler(Button_Click); instantiates an EventHandler delegate.