How to use delegates in C#

A simple guide to using delegates in C#.

It should be suitable for anybody but is particularly aimed at C/C++ programmers who are more used to using function pointers and function objects as a means of passing function parameters.

For the C/C++ equivalent of using callbacks see this link:

https://www.technical-recipes.com/2016/how-to-write-callbacks-in-c/

Step 1: declare the delegate

public delegate int Transform(int value);

Step 2: create methods for the delegate

public int DoubleValue(int value)
{
   return value * 2;
}

public int SquareValue(int value)
{
   return value * value;
}

Step 3: Instantiate the delegate and use it

TransformValue doubleValue = DoubleValue;

Full Code listing showing example usage

using System;

namespace Delegates
{
   internal class Program
   {
      #region Delegates

      public delegate int TransformValue(int value);

      #endregion

      public static int DoubleValue(int value)
      {
         return value * 2;
      }

      public static int SquareValue(int value)
      {
         return value * value;
      }

      private static void Main(string[] args)
      {
         TransformValue doubleValue = DoubleValue;
         TransformValue squareValue = SquareValue;

         const int Value = 10;

         Console.WriteLine("Value doubled = " + doubleValue(Value));
         Console.WriteLine("Value doubled = " + squareValue(Value));
      }
   }
}

Giving the following output as follows:

delegate

`