Pages

Search This Blog

Wednesday, January 21, 2015

Delegates

Delegates

Definition

A delegate (known as function pointer in C/C++) is a references type that invokes single/multiple method(s) through the delegate instance. It holds a reference of the methods. Delegate types are sealed and immutable type.
A delegate provides a way to encapsulate a method. Delegate type as being a bit like an interface with a single method. It specifies the signature of a method, and when you have a delegate instance, you can make a call to it as if it were a method with the same signature.
A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?". The answer boils down to giving you maximum flexibility to implement any functionality you want at runtime.
When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

Overview

Delegates have the following properties:
  • Delegates are like C++ function pointers but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods do not have to match the delegate type exactly
  • C# version 2.0 introduced the concept of Anonymous Methods, which allow code blocks to be passed as parameters in place of a separately defined method. C# 3.0 introduced lambda expressions as a more concise way of writing inline code blocks. Both anonymous methods and lambda expressions (in certain contexts) are compiled to delegate types. Together, these features are now known as anonymous functions.

Types

There are three types of delegates that can be used in C#.
  • Single Delegate
  • Multicast Delegate
  • Generic Delegate

Scenarios where can be used

·   Handle (call/invoke) multiple methods on a single event.
·   Define callback (asynchronous) methods.
·   Decoupling and implementing generic behaviors.
·   Invoke method at run time.
·   In LINQ for parsing the Expression Tree.

Syntax of Delegates

delegate <return type> <delegate-name> <parameter list>
public delegate int MyDelegate (string s);

Usage



using System;

namespace Samples
{

    //Declare delegate outside the class
    public delegate void mydelegate(int x, int y);

    class MyClass
    {
        //Declare a custom event
        public static event mydelegate myevent;
        public static void sum(int x, int y)
        {
            Console.WriteLine("Sum " + (x + y));
        }
        public static void diff(int x, int y)
        {
            Console.WriteLine("Diff " + (x - y));
        }
        //Raising event
        public static void RaiseEvent(int x, int y)
        {
            if (myevent != null)
            {
                myevent(x, y);
            }
        }

    }
    class MainClass
    {
        static void Main(string[] args)
        {
            //Instantiate delegate by passing a method name
            mydelegate del = new mydelegate(MyClass.sum);
            //attaching a method to delegate
            del += MyClass.diff;
            //As the above delegate holds reference of 2 methods ,
            //it is called as multicast delegate
            //calling a delegate
            del(10, 8);
            // alternate way to invoke a delegate
            del.Invoke(10, 10);
            //attaching a delegate to event
            MyClass.myevent += del;
            MyClass.RaiseEvent(10, 6);
            Console.Read();
        }
    }
}

No comments:

Post a Comment