DELEGATES IN C#

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C#  .NET 
C#
 501  View(s)
Ratings:
Rate this:
I want to use Delegates in c# please help me how to use this.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: 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.

    using System;

    delegate int ReplaceNumber(int n);
    namespace DelegateApp
    {
       class UseDelegate
       {
          static int number = 10;
          public static int AddNumber(int p)
          {
             number += p;
             return number;
          }

          public static int MultNumber(int q)
          {
             number *= q;
             return number;
          }
          public static int getNumber()
          {
             return number;
          }

          static void Main(string[] args)
          {
             //create delegate instances
             ReplaceNumber numberc1 = new ReplaceNumber(AddNumber);
             ReplaceNumber numberc2 = new ReplaceNumber(MultNumber);
            
             //calling the methods using the delegate objects
             numberc1(25);
             Console.WriteLine("First Value of Number: {0}", getNumber());
             numberc2(5);
             Console.WriteLine("Second Value of Number: {0}", getNumber());
             Console.ReadKey();
          }
       }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!