ISourceCode

Make the frequent cases fast and the rare case correct

C# example – (Single & Multicast) Delegate objects referencing named & anonymous methods.

The delegate keyword is used to declare a reference type that can be used to encapsulate a named or an anonymous method. – msdn.

Delegates are similar to function pointers in C++. Delegates are type safe something you would expect from a type safe language as C#. A delegate lets you pass a function as a parameter and is type safe since the function you pass as a delegate will have the same signature as the delegate declaration. Delegate types are sealed.In this article we can see how a delegate can be instantiated by associating it either with a named or anonymous method. Delegates are immutable.

I strongly recommend reading the code and understand how it works before absorbing the theory behind it. sometimes all the terminologies can get complicated but the code looks fairly simple and self understandable.

using System;
using System.Collections.Generic;
using System.Text;

namespace DelegatesDemo
{
    public delegate void Calculate(int x, int y);

    class Program
    {
        // Add method associated with the named delegate Calculate:
        // Add is instance method:
        public void Add(int x, int y)
        {
            int result = x + y;
            System.Console.WriteLine(" Addition : {0}", result);
        }
        // Sub method associated with the named delegate Calculate:
        // Sub is a static method
        public static void Sub(int x, int y)
        {
            int result = x - y;
            System.Console.WriteLine(" Subtraction : {0}", result);
        }

        static void Main()
        {
            Calculate a, b, c, d;

            // delegate object a referencing Add
            // The delegate instantiation using a named method Add
            // delegate mapped to instance method.
            Program pgm = new Program();
            // if you do not create a object of class to map the instance method it throws 
            // An object reference is required for the nonstatic field error.
            a = pgm.Add;

            // delegate object b that references Sub
            // delegate mapped to static method
            b = Sub;

            // Multicast delegate c two composed of a and b 
            c = a + b;

            // adding delegate b to c to call method Sub twice
            d = c + b;

            System.Console.WriteLine("Invoking named single delegate a:");
            // The delegate instantiation using a named method
            a(20,10);
            System.Console.WriteLine("Invoking named single delegate b:");
            b(20,10);
            System.Console.WriteLine("Invoking named multicast delegate c:");
            c(20,10);
            System.Console.WriteLine("Invoking named multicast delegate d:");
            d(20,10);

            // from composed delegate d remove b which calls only the method Add
            d = c - b;
            System.Console.WriteLine("Invoking name multicast delegate d after new reference:");
            d(20, 10);

            // Instatiate the delegate type using an anonymous method:
            System.Console.WriteLine("Invoking Anonymous delegate");
            Calculate p = delegate(int x, int y)
            {
                int result = x * y;
                System.Console.WriteLine(" Multiplication by anonymous method : {0}", result);
            };

            // anonymous delegate call which results in a multiplication
            p(30,40);
        }
    }
}

OUTPUT:

DelegatesDemo.exe
Invoking named single delegate a:
Addition : 30
Invoking named single delegate b:
Subtraction : 10
Invoking named multicast delegate c:
Addition : 30
Subtraction : 10
Invoking named multicast delegate d:
Addition : 30
Subtraction : 10
Subtraction : 10
Invoking name multicast delegate d after new reference:
Addition : 30
Invoking Anonymous delegate
Multiplication by anonymous method : 1200

generic delegates (not covered in this article) can also be created to define its own type parameters.

Using a delegate involves declaring, instantiating and calling it.
Following is the declaration of a delegate in the program.

public delegate void Calculate(int x, int y);

A delegate is derived from an abstract class called System.MulticastDelegate which is inherited from System.delegate abstract class. – msdn

A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. – msdn . In the code you can see delegates mapped to both static and instance methods.

Named & anonymous methods – A delegate is ideal for anonymous invocation since a method’s argument types and return type match the delegate’s argument types and return types, although this is flexible with use of covariance/contravariance. Code shows how a delegate can make reference to a named and anonymous methods. The named method can be either static or an instance method. Sometimes for example in threading creating a new method is undesirable and hence a code block can be defined immediately for a delegate to process this was introduced in C# 2.0 version. Code shows how anonymous method can be used.

Single & composing Multicast Delegate – apart from mapping a single delegate to a method. we can assign delegate objects in such a way that the delegate instance can multicast using the + operator. the delegate is thus composed of many delegates. The delegate calls the sub delegates it was composed from in a sequential order for example a delegate d = c + b calls method mapped by c and then b. Only delegates of the same type can be composed. Thus, remember multicast(composed) delegate holds the reference of more than one method. This multicast delegate stores all reference as linked list. All functions will call in sequence as they are assigned. Similarly the – operator can be used to remove a component delegate from a composed delegate.

Why Delegates?

Delegates are perfect for use as events.
delegates can be used to make asynchronous callbacks.

This leaves me with further work to write articles that answer these questions?

Use of delegates as events?
asynchronous callbacks and their use?

This article represents best of my understanding of delegates and related concepts from the internet resources. Any corrections are welcome.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: