What is Delegate in C#: Simple Explanation and Example
delegate is a type that holds a reference to a method, allowing methods to be passed as parameters or assigned to variables. It acts like a pointer to a function, enabling flexible and reusable code by calling methods indirectly.How It Works
Think of a delegate as a remote control for a TV. Instead of pressing buttons directly on the TV, you use the remote to tell the TV what to do. Similarly, a delegate holds a reference to a method and lets you call that method indirectly.
This means you can store methods in variables, pass them around, and call them later without knowing exactly which method will run. This is useful when you want to decide at runtime what action to perform, like choosing different TV channels with the same remote.
Example
This example shows how to declare a delegate, assign a method to it, and call the method through the delegate.
using System; // Declare a delegate type that takes an int and returns void public delegate void PrintNumber(int number); class Program { static void PrintSquare(int num) { Console.WriteLine($"Square: {num * num}"); } static void Main() { // Create a delegate instance pointing to PrintSquare PrintNumber printer = PrintSquare; // Call the method via delegate printer(5); } }
When to Use
Use delegates when you want to pass methods as arguments, define callback methods, or implement event handling. They help make your code flexible by allowing different methods to be called dynamically.
For example, in a button click event, a delegate can point to the method that runs when the button is clicked. Or when sorting a list, you can pass a delegate to decide how to compare items.
Key Points
- A delegate is a type-safe method reference.
- It allows methods to be assigned to variables and passed as parameters.
- Delegates enable flexible and reusable code patterns.
- They are commonly used for callbacks and event handling.