Skip to content

Instantiation and invocation

Context: Create a delegate instance by referencing a method (using the method name or a lambda). Invoke it like a method.

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);
d2("Hello"); // invokes Show
d3("World");

Always check for null before invoking a delegate.

if (d2 != null) d2("Safe");
// Or using null‑conditional operator
d2?.Invoke("Safe");

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.