Monday, November 5, 2018

Examples of C# delegates


This post is a brief introduction into the topic of C# delegates.


See the dictionary entry about delegate.

A delegate is a data type which can be instantiated and used as an object: especially when you need to pass a method as a parameter to another method, you will find delegates useful. Delegates are usually used in a situation of late binding, that is, when you don't know which method will be used in a particular place because there is more than one option and it depends on various aspects, such as the user's decisions.

The example below presents the use of a delegate in C#.
 

using System;
 
namespace ConsoleApp1
{
 public delegate int MyDelegate(string s);
 
 class Program
 {
  static void Main(string[] args)
  {
   /************* using delegates: *************/
   var delCall = new MyDelegate(ConvertStringToInt);
   Console.WriteLine(delCall("10"));
   Console.WriteLine(delCall("20"));
   /********************************************/

   /*********** not using delegates: ***********/
   Console.WriteLine(ConvertStringToInt("10"));
   Console.WriteLine(ConvertStringToInt("20"));
   /********************************************/
 
   Console.ReadKey();
  }

  public static int ConvertStringToInt(string text)
  {
   return Convert.ToInt32(text);
  }
 }
}




Notes

As you can see, a delegate can be declared outside of the class and instantiated in methods.

A delegate points to methods with identical parameter types and return type.

If you have several methods with the same name, the delegate will call a proper method (with a specific signature) depending on the context.

Since delegates are objects, they can also be posted as method parameters. 

Delegates are typically used when an event is called. 

No comments:

Post a Comment