Thursday, November 12, 2009

Delegates and events in C#

What are delegates and events in C# ? Delegates

Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.

Here are some features of delegates:

  • A delegate represents a class.
  • A delegate is type-safe.
  • We can use delegates both for static and instance methods
  • We can combine multiple delegates into a single delegate.
  • Delegates are often used in event-based programming, such as publish/subscribe.
  • We can use delegates in asynchronous-style programming.
  • We can define delegates inside or outside of classes.
  • Delegte declarations are like ordinary declerations and can be public, private internal etc.
  • Two delegates are compatible if their parameters are of the same type, order and modifiers and their return types are the same.
  • Delegates can be combined using the + and += operators. When two delegates are combined, the resulting delegate contains all the callable entities from both the delegates. Similarily, delegates can be removed using the - or -= operators.
  • Delegates can be compared.
  • delegate methods are invoked synchronously.
  • If such a delegate invocation includes reference parameters, each method invocation will occur with a reference to the same variable and changes to that variable by one method in the invocation list will be visible to methods further down the invocation list.
  • If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.
  • If an exception occurs within a delegate and the exception is not caught in the method that was called, continues in the method that called the delegate. If the exception is not handled in the called method, delegate processing is abandoned and other functions in the delegate are not called.

To declare a delegate, use the delegate keyword like:

    // declare a delegate
    public delegate void MyDelegate(int x); 

    /*
     * Declare a function which takes a 
     * delegate parameter. 
     */
    void MyFunc( MyDelegate inDelegateParam)
    {
         inDelegateParam(100); // Call the delegate
    }

    // Create a function with the same signature 
    // as the delegate decl
    void someFunc(int p)
    {
    }

    static void Main(string[] args)
    {
        MyDelegate aDel = new MyDelegate( someFunc);
        MyFunc( aDel );
    }

When we declare a delegate, the compiler automatically creates a class derrived from System.Delegate. A delegate instance encapsulates one or more methods, each of which is a callable entiry. For instance methods, the callable entity consists of the instance and the method.

When we invoke a delegate, all the callable entities get called.

Events

Delegates are used to create events. here is an example of an event

        // First declare a delegate
        public delegate void MyDelegate(int x);

        // now, the event
        public static event MyDelegate m_del;

        public static void testit()
        {
            m_del += new MyDelegate(EventFunc);
            m_del(2);
        }

        // This is the event handler
        static void EventFunc(int x)
        {
            Console.WriteLine("in event handler!!!!\n");
        }