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 [code language="csharp"] public delegate int Transform(int value); [/code] Step 2: create methods for the delegate [code language="csharp"] public int DoubleValue(int value) { return value * 2; } public int SquareValue(int value) { return value * value; } [/code] Step 3: Instantiate the delegate and use it [code language="csharp"] TransformValue doubleValue = DoubleValue; [/code] Full Code listing showing example usage [code language="csharp"] 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)); } } } [/code] Giving the following output as follows: delegate

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with client-server applications in C++

How to send an e-mail via Google SMTP using C#