Delegates let you store references to methods. This helps you call methods indirectly and pass them around like variables.
Delegate declaration and instantiation in C Sharp (C#)
delegate return_type DelegateName(parameter_list);
DelegateName delegateInstance = new DelegateName(MethodName);The delegate keyword declares a delegate type.
Delegate instances are created by passing a method name matching the delegate signature.
SayHello.delegate void SimpleDelegate(); void SayHello() { Console.WriteLine("Hello!"); } SimpleDelegate d = new SimpleDelegate(SayHello);
Add method.delegate int MathOperation(int x, int y); int Add(int x, int y) { return x + y; } MathOperation op = new MathOperation(Add);
This program declares a delegate GreetDelegate for methods that take a string and return nothing. It creates instances pointing to two different greeting methods and calls them.
using System; class Program { delegate void GreetDelegate(string name); static void GreetMorning(string name) { Console.WriteLine($"Good morning, {name}!"); } static void GreetEvening(string name) { Console.WriteLine($"Good evening, {name}!"); } static void Main() { GreetDelegate greet = new GreetDelegate(GreetMorning); greet("Alice"); greet = new GreetDelegate(GreetEvening); greet("Bob"); } }
Delegate method signatures must match exactly (parameters and return type).
You can use shorthand syntax: GreetDelegate greet = GreetMorning; without new.
Delegates can point to multiple methods using multicast, but that is an advanced topic.
Delegates hold references to methods with a specific signature.
Declare delegates with the delegate keyword and instantiate by passing a method name.
Delegates enable flexible and reusable code by allowing methods to be passed and called indirectly.