Monday, June 07, 2010

C# Delegates

Delegate Example 1

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

namespace DelgateForNotes
{
class Program
{
// Declaring A delegate , which will refer function having two parameter and will return integer
public delegate int AddDelegate(int num1, int num2);


static void Main(string[] args)
{
// Creating method of delegate, and passing Function Add as argument.
AddDelegate funct1= new AddDelegate(Add);
// Invoking Delegate.....
int k=funct1(7,2);
Console.WriteLine(" Sumation = {0}",k);
Console.Read();

}
// Static Function Add, which having same signature as of delegate
public static int Add(int num1, int num2)
{
Console.WriteLine("I am called by Delegate");
int sumation;
sumation= num1+ num2;
return sumation;
}
}
}
Output:
I am called by Delegate
Sumation =9

MultiCast Delegates

A delegate which wrap up more than one method is called Multicast Delegates. When a multicast delegate is get called, it will successively call each functions in order. Multicast Delegate allow to chain together several functions. These chain functions can be called together when delegate is invoked. Every Delegate type has a built in support for dealing with multiiple handlers. Delegate gets this support by inheriting from the MultiCastDelegate class.
To work with Multicast Delegate , delegate signature should return void. Otherwise only last method result can be fetched.
Operators used are
+= this operator is used to add functions in delegate .
-= this operatir is used to remove function from delegate.

Delegate classes

System.Delegate

The purpose of a single delegate instance is very similar to a method pointer from C++. However, in C# don't use method pointers, rather, it save the "metadata" that identifies the target method to call. System.Delegate contains two critical data elements. Firstly, it contains an instance of System.Reflection.MethodInfo â?" in other words, the .NET metadata that enables method invocation using reflection.
The second aspect of System.Delegate is the object instance on which the method needs to be invoked. Given an unlimited number of objects that could support a method that matches the MethodInfo signature, we also need to be able to identify which objects to notify. The only exception is when the method identified by MethodInfo is static â?" in which case the object reference stored by System.Delegate is null.

System.MulticastDelegate

System.MulticastDelegate therefore, adds to delegates the support for notifying multiple subscribers. This is enabled through System.MulticastDelegate's containment of another System.MulticastDelegate instance. On adding a subscriber to a multicast delegate, the MulticastDelegate class creates a new instance of the delegate type, stores the object reference and the method pointer for the added method into the new instance, and adds the new delegate instance as the next item in a list of delegate instances. In effect, the MulticastDelegate class maintains a linked list of delegate objects.

Sequential Invocation

When invoking the multicast delegate, each delegate instance in the linked list is called sequentially. This sequential invocation, however, leads to problems if the invoked method throws an exception or if the delegate itself returns data.

Multicast Delegate Example 1

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


namespace MulticastDelegate1
{
class Program
{
// Decelaring delegate here, which will refer to method having void return type and one string as argument
public delegate void showDelegate(string s);
static void Main(string[] args)
{
showDelegate s = Display;
s += Show;
s("Hello");
s("Scott");
Console.Read();
}

// User Defind static function to display
public static void Display(string title)
{
Console.WriteLine(title);
}

// User defind static function
public static void Show(string title)
{
Console.WriteLine(title);
}

}
}
OUTPUT:
Hello
Hello
Scott
Scott

In the above example, the showDelegate is a delegate, which can refer any method having return type void and one string as parameter. There are two static user defined functions called Display and Show.

Multicast Delegate Example 2

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

namespace MulticastDelegate
{
// user defined class for math operation. This class contains two static method. one method for squre and another method for double the number.
class MathOperation
{
// Multiply by two method, this method multiply number by 2
public static void MultiplyByTwo(double d)
{
double res = d*2;
Console.WriteLine("Multiply: "+res.ToString());

}
// squre number method
public static void Squre(double e)
{
double res = e * e;
Console.WriteLine("Square"+res.ToString());
}
}

class NewProgram
{
// Decelaring delegate called del
public delegate void del(double Qr);

static void Main()
{
// Creating delegate
del d = MathOperation.MultiplyByTwo;
// adding method to del delegate using += operator
d += MathOperation.Squre;
// calling display function. passsing delegate and double value as parameter
Display(d, 2.00);
Display(d, 9.9);
Console.ReadLine();
}

// User defined function to display result and call appropirate operation
static void Display(del action, double value)
{
Console.WriteLine("Result = "+ value);
action(value);
}
}

The above code is implementing multicast delegate. In above code, there is a MathOperationClass, this class is containing two methods. One to double the input parameter and other to make squre of that.

public delegate void del(double Qr);

This is delegate decelaration. It will refer method having one double parameter and will return void.

Display function is taking delegate and double as parameter. This function is displaying the result and calling the delegate.


Article from: http://www.dotnetspark.com/kb/1218-beginners-guide-to-delegates-c-sharp.aspx