Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Delegates in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 459
    Comment on it

    Delegates in C#

    1) Delegate is a kind of function pointer as we have in C or C++.

    2) It holds the reference to a method.

    3) Reference to a method can be changed at run-time.

    4) We can add or remove reference to method using += and -= respectively.

    5) It is used to implement events and callbacks.

    6) It can refer to any method having same signature as that of delegate itself.

    7) Effective use lead to performance improvements throughout the application.

    Example

    delegate double MyMethod(int a, int b); // Declaration of delegate
    
    class Area
    {
       public static double Rectangle(int l, int b) // Same signature like delegate's
       {
         return l*b;
       }
       public static double Triangle(int b, int h) // Same signature like delegate's
       {
         return (0.5*b*h);
       }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyMethod methodArea = Area.Rectangle;
            Console.WriteLine("Area is -:"+ methodArea(10, 5)); // It will call Rectangle.
            methodArea += Area.Triangle;
            Console.WriteLine("Area is -:" + methodArea(10, 5)); // It will call Triangle.
            methodArea -= Area.Triangle;
            Console.WriteLine("Area is -:" + methodArea(10, 5)); // It will call Rectangle.
            Console.ReadKey();
         }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: