CSharp Guide : What is Delegate in C# with Example
What is Delegate in C# with Example : Delegates are a fundamental and powerful feature in C#, often considered as pointers to functions. C# Delegate provide a way to encapsulate a method call and are pivotal in implementing event handling and callback methods. In this blog post, we’ll dive deep into what delegates are, how they work, and how you can use them with real-time examples.
Table of Contents
Understanding Delegate in C#
What is a Delegate in C#?
In C#, a delegate is a type that specifies a method signature. It can reference a method with a matching signature, meaning the method must have the same return type and parameter list. This makes delegates similar to function pointers in C and C++ but safer and more secure.
Learn about Design Patterns in c# with Examples.
Key Points about Delegates:
- Delegates are type-safe.
- They can reference both static and instance methods.
- Delegates can be chained together, allowing multiple methods to be invoked from a single event.
- Delegates are often used in designing extensible and flexible applications (e.g., in event handling in Windows Forms).
Syntax of Delegates
To declare a delegate, you use the delegate
keyword, followed by a return type and a parameter list. Here’s a simple example:
This declaration defines a delegate named MyDelegate
that can reference any method that takes a single string
parameter and returns void
.
Basic Delegate in C# Example
Let’s look at a basic example to understand how delegates work. Consider the following program:
using System;
namespace DelegateExample
{
class Program
{
// Step 1: Declare a delegate
public delegate void DisplayMessage(string message);
static void Main(string[] args)
{
// Step 2: Instantiate the delegate
DisplayMessage messageDelegate = ShowMessage;
// Step 3: Call the delegate
messageDelegate("Hello, World!");
// Step 4: Use delegate with another method
messageDelegate += DisplayAnotherMessage;
messageDelegate("Hello again!");
}
// Method that matches the delegate signature
public static void ShowMessage(string message)
{
Console.WriteLine(message);
}
// Another method that matches the delegate signature
public static void DisplayAnotherMessage(string message)
{
Console.WriteLine($"Another message: {message}");
}
}
}
Explanation
- Step 1: We declare a delegate named
DisplayMessage
. - Step 2: We create an instance of the delegate and assign it to the
ShowMessage
method. - Step 3: We call the delegate, which in turn calls the
ShowMessage
method. - Step 4: We add another method to the delegate invocation list using the
+=
operator, demonstrating multicast delegates.
Real-Time Example: Using Delegates for Callbacks
In real-world applications, delegates are extensively used for implementing callbacks. For instance, you might have a method that performs a long-running task and need to notify the calling code when the task is complete.
Here you can learn about Dependency Injection in .NET Core with Example.
Here’s a practical example:
using System;
using System.Threading;
namespace DelegateCallbackExample
{
class Program
{
// Define a delegate for callback
public delegate void NotifyCallback(string result);
static void Main(string[] args)
{
Console.WriteLine("Starting task...");
// Start a long-running task
LongRunningTask(TaskCompleted);
Console.WriteLine("Task started. Waiting for completion...");
}
// Method to simulate a long-running task
public static void LongRunningTask(NotifyCallback callback)
{
Thread.Sleep(5000); // Simulate a task taking 5 seconds
// Task is complete, proceed to invoke the callback.
callback("Task completed successfully!");
}
// Callback method
public static void TaskCompleted(string result)
{
Console.WriteLine(result);
}
}
}
Explanation
- Delegate Definition:
NotifyCallback
is a delegate type for the callback. - LongRunningTask Method: This method simulates a long task using
Thread.Sleep
. - Callback Invocation: Once the task is complete, the delegate
callback
is invoked. - Main Method: The
LongRunningTask
is called withTaskCompleted
as the callback method.
Advanced Use Case: Event Handling with Delegates
Delegates serve as the cornerstone of event handling in C#. Events are special multicast delegates that are used to broadcast a message to multiple subscribers. Here’s how you can use delegates for event handling:
Step-by-Step Example
using System;
namespace EventHandlingExample
{
// Defines a delegate for the event handler
public delegate void NotifiesEventHandler(object sender, EventArgs e);
// Define a publisher class
public class Publisher
{
// Declare the event using the delegate
public event NotifiesEventHandler Notify;
public void RaiseEvent()
{
// Check if there are any subscribers
if (Notify != null)
{
Notify(this, EventArgs.Empty);
}
}
}
// Define a subscriber class
public class Subscriber
{
public void OnNotify(object sender, EventArgs e)
{
Console.WriteLine("Event received by Subscriber.");
}
}
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
// Subscribe to the event
publisher.Notify += subscriber.OnNotify;
// Raise the event
publisher.RaiseEvent();
}
}
}
Explanation
- Delegate Definition:
NotifiesEventHandler
is a delegate type for the event. - Publisher Class: This class declares an event named
Notify
using the delegate. - RaiseEvent Method: This method raises the event, checking if there are any subscribers.
- Subscriber Class: This class has a method
OnNotify
that handles the event. - Main Method: The
Publisher
raises the event, which is handled by theSubscriber
.
Conclusion
Delegates are a powerful feature in C#, enabling flexible and reusable code. They allow methods to be passed as parameters and support asynchronous programming patterns like callbacks and events. By understanding and utilizing delegates, you can write more robust and maintainable C# applications.
In this post, we covered:
- The basic concept and syntax of delegates.
- A simple delegate example.
- A real-time example using delegates for callbacks.
- How to use delegates for event handling.
By applying these concepts, you can leverage the full potential of delegates in your C# programming. Whether you are implementing simple callbacks or complex event-driven architectures, delegates provide a robust mechanism for method abstraction and execution.
Service Tag: – Csharpmaster | Csharp Master | c# quiz | Fluent Validation in .NET Core | monolithic and microservices architecture | Global Exception Handler in .NET Core | HashMap in C# | Dictionary in C# | split string in c# |Open Closed Principle in C#| liskov substitution principle c# example | Difference Between Async and Await in C# | Difference Between String and StringBuilder in C# | What is Delegate in C# with Example | dependency injection in .NET Core | Lambda Expression in C# | Design Patterns in C# with Examples | Boxing and Unboxing in C# with Example | Collection in C# with Example | How to split string in ca comprehensive guide | Implement open closed principle in csharp example | Difference between async and await in c with-example | string and stringbuilder in csharp with example csharp master tutorial | lambda expression in c with example
- Enum Data Type in PostgreSQL with Practical Examples
- Understanding the Repository Design Pattern in C#
- What is DTO in C# with Example | Data Transfer Object Design Pattern | C# Master
- Understanding POCO Class in C#
- CSharpMaster’s C# Quiz for Beginner
- Using Fluent Validation in .NET Core 8 with Example
- CsharpMaster – Difference Between Monolithic and Microservices Architecture with Example
- Csharp Master – Global Exception Handler in .NET Core 7 & .Net Core 8 Web API (2024)
- Understanding What is HashMap in C# with Example (2024)
- CSharp Master’s Guide to Using Dictionary in C# (Key-value pair) – 2024
- CSharpMaster – How to Split String in C# (String.Split() with string delimiter)
- CSharpMaster – How to Implement Open Closed Principle in C# Example (SOLID)
- Understanding liskov principle c# | liskov substitution principle c# example
- Difference Between Async and Await in C# with Example – C# asynchronous programming 2024
- Difference Between String and StringBuilder in C# with example – Csharp Master Tutorial