Delegates - CE10 Blog

Download Report

Transcript Delegates - CE10 Blog

Delegates
“Delegates and Events” of
Professional C# 2005 [Wrox]
Topic-3








Delegates and events
3.1 Delegates
Definition & declaration
Using delegate in C#
Simple delegate example
3.2 Anonymous method
3.3 Events
Generating events
2
The Concept


Consider delegate as an object that
contains a list of methods with the same
signature and return type
When a delegate is called, each method in
the list gets executed
Delegate
Method1
Method2
Method3
Method4
3
Points

The methods can be of any class

Methods can be static or instance type

A delegate is a type just as a class or a
struct

Delegates are always type safe
4
Declaration

Looks much like the declaration of a
method
delegate void MyDelegate( int x );

Creating a delegate object is similar to
creating any other object
MyDelegate myDel;
mydel = new MyDelegate(method1);

You can also use the shortcut syntax as
MyDelegate myDel = method1;
5
Example
class Example{
delegate int DlgNumber(int n);
static int GetNN(int n)
{
return (n+1);
}
static void Main(){
DlgNumber dlgN = GetNN;
}
}
//Invoke the delegate
C.WL( dlgN(123) );
6
Example












namespace MyFirstDelegate
{
//This delegate can point to any method,
//taking two integers and returning an integer
public delegate int MyDelegate(int x, int y);
//This class contains methods that MyDelegate will
point to.
public class MyClass
{
public static int Add(int x, int y)
{
return x + y;
}
7
Example












public static int Multiply(int x, int y)
{
return x * y;
}
}
class Program
{
static void Main(string[] args)
{
//Create an Instance of MyDelegate
//that points to MyClass.Add().
MyDelegate del1 = new
MyDelegate(MyClass.Add);
8
Example












//Invoke Add() method using the delegate.
int addResult = del1(5, 5);
Console.WriteLine("5 + 5 = {0}\n", addResult);
//Create an Instance of MyDelegate
//that points to MyClass.Multiply().
MyDelegate del2 = new
MyDelegate(MyClass.Multiply);
//Invoke Multiply() method using the delegate.
int multiplyResult = del2(5, 5);
Console.WriteLine("5 X 5 = {0}", multiplyResult);
Console.ReadLine();
}
}
9
Delegate ability to Multicast


Delegate's ability to multicast means that a delegate
object can maintain a list of methods to call, rather than a
single method if you want to add a method to the
invocation list of a delegate object , you simply make use
of the overloaded += operator, and if you want to remove
a method from the invocation list you make use of the
overloaded operator -= .
Note: The Multicast delegate here contain methods that
return void, if you want to create a multicast delegate
with return type you will get the return type of the last
method in the invocation list.
10
Multicast Delegates




When a delegate wraps more than one
method, it is known as a multicast delegate
Successively calls each method in order
Should return a void
To append methods, use the + or +=
operator
Eg:
OR
DelegateDemo dd1 = Method1;
DelegateDemo dd2 = Method2;
DelegateDemo ddd = dd1 + dd2;
ddd = Method1;
ddd += Method2;
11
Multicast Delegates
















namespace MyMulticastDelegate {
//this delegate will be used to call more than one method at once
public delegate void MulticastDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static void Add(int x, int y)
{
Console.WriteLine("You are in Add() Method");
Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);
}
public static void Multiply(int x, int y)
{
Console.WriteLine("You are in Multiply() Method");
Console.WriteLine("{0} X {1} = {2}", x, y, x * y);
12
}}
Multicast Delegates
class Program {

static void Main(string[] args)

{

MulticastDelegate del = new MulticastDelegate(MyClass.Add);

del += new MulticastDelegate(MyClass.Multiply);
Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");

del(5, 5);

//removing the Add() method from the invocation list

del -= new MulticastDelegate(MyClass.Add);

Console.WriteLine("\n\n****Add() Method removed.****\n\n");

//this will invoke the Multibly() method only.

del(5, 5);

}

}

}

13
Anonymous Method




An anonymous method is a method
without any name.
To understand better, a normal method is
one which will have a name, return type
optionally arguments and an access
modifier.
So, an anonymous method in C# is a
feature to have methods without name.
Anonymous methods can be used in the
place where there is a use of a delegate.
14
Anonymous Methods

Creates a method and adds it to delegate



treated the same as other methods
good for one-time, short delegates
An anonymous methods is a block of code
that is used as the parameter for the
delegate.
15
Anonymous Methods

The syntax of an anonymous method
consists of the keyword delegate, an
optional parameter list and method body
enclosed in parenthesis.
delegate(optional parameters)
{
Body of the method.
};
16
Anonymous Methods















class program
{
delegate string delegateTest(string val);
static void Main(string[] args)
{
string mid = ", mid part,";
delegateTest annodel = delegate(string param)
{
param += mid;
param += " and this was added to the string.";
return param;
};
Console.WriteLine(annodel("start of the string"));
}
}
}
17
Anonymous Methods















namespace consoleappliction
{ delegate void CountIt();
class AnonMethod
{
static void Main()
{
CountIt count = delegate
{
for(int i=0; i<=5; i++)
{
Console.WriteLine(i);
}
};
count();
} } }
18
Events




Built upon the foundation of delegate is
another important C# feature: the event.
An event is essentially, an automatic
notification that some action has occurred.
Events work like this: An object that has an
interest in an event registers an event
handler for that event. When the event
occurs, all registered handler are called.
Event handler are represented by
delegate.
19
Examples




Clicking a button
Not clicking a button
Selecting a menu
Not selecting a menu
20
Publish and Subscribe




An object publishes a set of events to
which other classes can subscribe.
When the publishing class raises an event,
all the subscribed classes are notified.
Events provide a way for a class or an
object to notify other classes or objects
when something of interest happens.
The class that sends the event is called
the publisher and the classes that receive
the event are called subscribers.
21
Publish and Subscribe
22
The Delegate Connection




Events in C# are implemented with
delegates.
The publishing class defines a delegate
that the subscribing classes must
implement.
When the event is raised, the subscribing
class's methods are invoked through the
delegate.
A method that handles an event is called
an event handler.
23
Question
Is the event handler a delegate?
Ans. YES
24
Event Handlers


Return type  void
Parameters





Source of the event
An object derived from EventArgs
EventArgs is the base class for all event
data.
The EventArgs derived class contains
information about the event.
EXAMPLE
25
Conventions





The following important conventions are used with events:
Event Handlers in the .NET Framework return void and
take two parameters.
The first paramter is the source of the event; that is the
publishing object.
The second parameter is an object derived from
EventArgs.
Events are properties of the class publishing the event.
The keyword event controls how the event property is
accessed by the subscribing classes.
26
Example
using System.Text;
public delegate void Edelegate();
class Program
{
public event Edelegate eve;
public void first()
{
Console.WriteLine(" I am first");
}
public void second()
{
Console.WriteLine(" I am second");
}
public void Third()
{
Console.WriteLine(" I am Third");
}
public void evecall()
{
if (eve!=null)
eve();
}
}
27
class demo
{
static void Main(string[] args)
{
Program p = new Program();
p.eve +=new Edelegate(p.first);
p.evecall();
Console.WriteLine("---------");
p.eve += new Edelegate(p.second);
p.evecall();
Console.WriteLine("---------");
p.eve += new Edelegate(p.Third);
p.evecall();
}
}
28
Covariance and Contravariance


Covariance enables a method to be assigned to a
delegate when the method’s return type is a class
derived from the class specified by the return type of the
delegate.
Contravariance enables a method to be assigned to a
delegate when the method’s parameter type is a base
class of the class specified by the delegate’s declaration.
29