Delegates With Examples in C#

Simple Delegates With Examples.
Delegates have the following properties:
  1. Delegates are similar to C++ function pointers, but are type safe.
  2. Delegates allow methods to be passed as parameters.
  3. Delegates can be used to define callback methods.
  4. Delegates can be chained together; for example, multiple methods can be called on a single event.
  5. Methods don't need to match the delegate signature exactly.
  6. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that can call the referenced method, without having to know at compile time which method will be invoked.
  7. An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
Example 1

using System;
 
 
namespace Delegates_CSharp
{
    class Program
    {
        // declare delegate
        public delegate void Print(int value);
 
        static void Main(string[] args)
        {
            // Print delegate points to PrintNumber
            Print printDel;
 
            printDel = PrintNumber;
 
            printDel(100000);
            printDel(200);
 
            // Print delegate points to PrintMoney
            printDel = PrintMoney;
 
            printDel(10000);
            printDel(200);
 
            Console.ReadKey();
        }
 
        public static void PrintNumber(int num)
        {
            Console.WriteLine("Number: {0,-12:N0}", num);
        }
 
        public static void PrintMoney(int money)
        {
            Console.WriteLine("Money: {0:C}", money);
        }
 
    }
}


Example 2

using System;
 
delegate int NumberChanger(int n);
 
namespace MulticastDelegate_CSharp
{
    class Program
    {
        static int num = 10;
 
        public static int AddNum(int p)
        {
            num += p;
            return num;
        }
        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
        static void Main(string[] args)
        {
            //create delegate instances
            NumberChanger nc;
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);
 
            nc = nc1;
            nc += nc2;
 
            //calling multicast
            nc(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}

Comments

Popular posts from this blog

Visual Basic 6 (VB6) Operators

C# Delegates simple example in .NET

Control Structures In Visual Basic 6.0