Delegates in C# is simply a reference/pointer to a function . One of the typical usage of the delegates is the event handlers in .NET.

Example of Delegates in C#

Below is a sample code snippet demonstrating the usage of delegates to add and subtract 2 numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ACSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Example of Delegates in C#
            ACDelegate del = AddNumbers;
            Console.WriteLine("Add Method : " + del(1,2));
            del = Subtract;
            Console.WriteLine("Add Method : " + del(1, 2));
            Console.ReadLine();
        }
        public delegate int ACDelegate(int a, int b);
        public static int AddNumbers(int a , int b)
        {
            return a + b;
        }
        public static int Subtract(int a, int b)
        {
            return a - b;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Liked this content?. Please spread the word :)

  • RSS
  • Twitter
    Visit Us
    Follow Me