Wednesday, 21 March 2018

Delegates in C#


C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

A delegate holds a reference to a method and also to the target object on which the method should be called. A delegate in C# is similar to function pointers of C++, but C# delegates are type safe. You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the "delegate" keyword. You can declare a delegate that can appear on its own or even nested inside a class.


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

namespace Delegate_Examples
{
    delegate int Numberchange(int n);
    class Program
    {
        static int Num = 10;
        public static int Addnum(int i)
        {
            Num += i ;
            return Num;
        }
        static void Main(string[] args)
        {
            Numberchange NC = new Numberchange(Addnum);
            var result = NC(20);
            Console.WriteLine("{0}",result);
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment

Azure Service Bus Queue , Table - Send, Read

using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; ...