---
title: "What are delegates and their uses? Also, give an example."  
description: "What are delegates and their uses? Also, give an example."  
author: "Revati S Misra"  
published: 2023-04-14  
updated: 2023-04-19  
canonical: https://www.mindstick.com/forum/157792/what-are-delegates-and-their-uses-also-give-an-example  
category: "oops"  
tags: ["c#", "oops", "delegates"]  
reading_time: 1 minute  

---

# What are delegates and their uses? Also, give an example.

What are delegates and their uses? Also, give an example.

## Replies

### Reply by Sanjay Goenka

In C#, a delegate is a type that represents a method signature. Delegates allow you to treat methods as objects, which can be passed as arguments to other methods or stored as variables. Delegates provide a way to implement the observer pattern and to write callback functions.

```cs
public delegate void MyDelegate(string message);
public class MyClass
{
  public void MethodA(string message)
  {
      Console.WriteLine($"MethodA: {message}");
  }
  public void MethodB(string message)
  {
      Console.WriteLine($"MethodB: {message}");
  }
}
public class Program
{
  public static void Main()
  {
      MyClass obj = new MyClass();
      MyDelegate del1 = new MyDelegate(obj.MethodA);
      MyDelegate del2 = new MyDelegate(obj.MethodB);
      // Call the delegate with different messages
      del1("Hello");
      del2("World");
  }
}
```

In this example, we define a delegate named "MyDelegate" that takes a single string parameter and returns void. We also define a class "MyClass" that contains two methods, "MethodA" and "MethodB", that match the signature of the delegate.


---

Original Source: https://www.mindstick.com/forum/157792/what-are-delegates-and-their-uses-also-give-an-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
