Delegates C#
Delegates C#
Delegate's word meaning is representative. A delegate in .Net is juts like a function pointer in C#.
The most important property of a function pointer is that the syntax of the function and the pointer to the function
must exactly be same. The returntypes and the list of arguments must match exactly.
When we use delegate then there are 3 stages which we need to follow:
1)Declaration:
2)Instantiation:
3)Invoking:
1) When we want to create the controls dynamically, then we cannot create the events for these controls
beforehand as these controls are created only on runtime. In that case, if we want to bind these controls with
2. Creating the delegate object and assigning methods to those delegate objects
Both delegates and interfaces allow a class designer to separate type declarations and implementation. A
given interface can be inherited and implemented by any class or struct; a delegate can created for a method
on any class, as long as the method fits the method signature for the delegate. An interface reference or a
delegate can be used by an object with no knowledge of the class that implements the interface or delegate
method. Given these similarities, when should a class designer use a delegate and when should they use an
interface?
Example:1)
bo(10,20);
bo1(30,2);
Console.ReadLine();
}
}
Output:
30
28
2)Program that demonstrates delegate type [C#]
using System;
class Program
{
delegate string UppercaseDelegate(string input);
Multicasting:
Multicasting is the ability to create an invocation list, or chain, of methods that will be automatically called when
a delegate is invoked. Such a chain can be created by instantiating a delegate and then use the + or +=
operator to add methods to the chain. To remove a method, use –or -=. If the delegate returns a value then the
value returned by last delegate in the list becomes the return value of the entire delegate invocation. Thus a
delegate that makes use of multicasting will often have a void return type.
Example 1 :
Output:
This Is method 1
This is method 2
This Is method 1
Example 2:
class Rooster {
internal void Crow(){
Console.WriteLine("Cock-a-doodle-doo");
}
}
class PaperBoy {
internal void DeliverPapers(){
Console.WriteLine("Throw paper on roof");
}
}
class Sun {
internal void Rise(){
Console.WriteLine("Spread rosy fingers");
}
}
class DawnRoutine
{
delegate void DawnBehavior();
DawnBehavior multicast;
DawnRoutine()
{
multicast = new DawnBehavior(new Rooster().Crow);
multicast += new DawnBehavior(
new PaperBoy().DeliverPapers);
multicast += new DawnBehavior(new Sun().Rise);
}
void Break(){
multicast();
}
public static void Main()
{
DawnRoutine dr = new DawnRoutine();
dr.Break();
Console.ReadLine();
}
}
}
Output:
Cock-a-doodle-doo
Throw paper on roof
Spread rosy fingers