How to Create Delegate in C#: Syntax and Example
In C#, create a delegate by declaring it with the
delegate keyword followed by a method signature. Then, instantiate it by assigning a method matching that signature. Delegates allow you to pass methods as parameters or store them as variables.Syntax
A delegate declaration starts with the delegate keyword, followed by the return type and the parameter list matching the methods it can point to. For example, delegate void MyDelegate(string message); declares a delegate that points to methods returning void and taking a string parameter.
To use it, create an instance by assigning a method with the same signature, then invoke it like a method.
csharp
delegate void MyDelegate(string message);Example
This example shows how to declare a delegate, assign a method to it, and invoke the delegate to print a message.
csharp
using System; class Program { // Declare a delegate type delegate void MyDelegate(string message); // Method matching the delegate signature static void ShowMessage(string msg) { Console.WriteLine(msg); } static void Main() { // Create delegate instance pointing to ShowMessage MyDelegate del = ShowMessage; // Invoke the delegate del("Hello from delegate!"); } }
Output
Hello from delegate!
Common Pitfalls
- Signature mismatch: The method assigned to a delegate must exactly match the delegate's return type and parameters.
- Null delegate invocation: Invoking a delegate that is
nullcauses a runtime error; always check or use the null-conditional operator. - Using delegate instead of event: For event handling, use
eventkeyword with delegates to restrict direct invocation.
csharp
using System; class Program { delegate void MyDelegate(string message); static void ShowMessage(int number) // Wrong signature { Console.WriteLine(number); } static void Main() { // Compilation error: signature mismatch // MyDelegate del = ShowMessage; // Correct usage: MyDelegate del = msg => Console.WriteLine(msg); // Null check before invoking del?.Invoke("Safe call"); } }
Output
Safe call
Quick Reference
Remember these key points when working with delegates:
- Declare with
delegatekeyword and method signature. - Assign methods with matching signature.
- Invoke delegates like methods.
- Check for
nullbefore invoking. - Use
eventkeyword for event patterns.
Key Takeaways
Declare delegates using the delegate keyword with a matching method signature.
Assign methods to delegates only if their signatures match exactly.
Always check if a delegate is null before invoking it to avoid runtime errors.
Use delegates to pass methods as parameters or store them as variables.
For event handling, combine delegates with the event keyword for safety.