Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can...

22
Dl t Delegates A delegate is an object that can refer to a method. A delegate is an object that can refer to a method. Creating delegate, actually creating an object that can hold a reference to a method. The method can be called through this reference. A delegate can invoke the method to which it refers. Same delegate can be used to call different methods during runtime of a program by simply changing the method to which the delegate refers. the delegate refers. thus, the method that will be invoked by a delegate is not determined at compile time but rather run time. This is the i i l d t f dl t principal advantage of a delegate. 266 © http://www.ashishpal.wordpress.com

Transcript of Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can...

Page 1: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

D l tDelegates A delegate is an object that can refer to a method.A delegate is an object that can refer to a method.

Creating delegate, actually creating an object that can hold a reference to a method.

The method can be called through this reference. A delegate can invoke the method to which it refers.

Same delegate can be used to call different methods during runtime of a program by simply changing the method to which the delegate refers.the delegate refers.

thus, the method that will be invoked by a delegate is not determined at compile time but rather run time. This is the

i i l d t f d l tprincipal advantage of a delegate.266© http://www.ashishpal.wordpress.com

Page 2: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Syntax of a delegate declaration:Syntax of a delegate declaration:delegate ret-type name (parameter-list)

ret-type is the type of the value returned by the methods that theret type is the type of the value returned by the methods that the delegate will be calling.

The parameters required by the methods called through the d l t ifi d i th t li tdelegate are specified in the parameter-list.

Once created, a delegate instance can refer to and call methods whose return type and parameter-list match those specified in thewhose return type and parameter list match those specified in the delegate declaration.

A delegate can be used to call any method that agrees with its i t d t t Th th d b ith i tsignature and return type. The method can be either an instance

method associated with an object or a static method associated with a class. All that matters is that the return type and signature of the method agrees with those of the delegate.

267© http://www.ashishpal.wordpress.com

Page 3: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

A Delegate is a special user defined type that is declared l b ll lik lglobally, like a class.

Created like an interface, it provides a template for a method., p p

Like interface, a delegate is not defined. Its role is to show what a useful method would look likeuseful method would look like.

Delegates can be specified in their own namespace, or else can b ifi d ithi th lbe specified within another class.

Each delegate is limited to referencing methods of a particular g g pkind only.

Function Pointers of C & C++

Delegates in .NET Framework

Callback functions of Microsoft Win32

Library Programming 268© http://www.ashishpal.wordpress.com

Page 4: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Delegates in actionusing System;

//declaring a delegate type.delegate string StrMod(string str);g g gClass DelegateTest {

//replaces space with hyphens.static string ReplaceSpaces(string s) {Console.WriteLine(“Replacing spaces with hyphens.”);return s.Replace(‘ ‘,’-’);}

//remove spaces.static string RemoveSpaces(string s) {static string RemoveSpaces(string s) {string temp = “”;int i;Console.WriteLine(“Removing Spaces.”);for ( i=0; i < s.Length ; i++)if(s[i] != ‘ ‘) temp += s[i];( [ ] ) p [ ];return temp;}

//reverse a string.static string reverse(string s) {t i t “”string temp = “”;

int i, j;Console.WriteLine(“Reversing the string.”); 269© http://www.ashishpal.wordpress.com

Page 5: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

for (j=0 , i = s.Length-1; i>=0; i-- , j++) temp += s[i];

return temp;}}

static void Main() {//Construct a delegate.

StrMod strOp = new StrMod (ReplaceSpaces );string str;

//call methods through the delegates.str = strOp(“This is a test ”);str = strOp( This is a test. );Console.WriteLine(“Resulting String: “ + str);

strOp = new StrMod ( RemoveSpaces );str = strOp(“This is a test.”);Console.WriteLine(“Resulting String: “ + str);( g g )

strOp = new StrMod ( reverse );str = strOp(“This is a test.”);Console.WriteLine(“Resulting String: “ + str);

}}}

270© http://www.ashishpal.wordpress.com

Page 6: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

The output of this program is:p p g

Replacing spaces with hyphens.Resulting String: This-is-a-test.

Removing spaces.R lti St i Thi i t tResulting String: Thisisatest.

Reversing the string.Resulting String: .tset a si sihT

271© http://www.ashishpal.wordpress.com

Page 7: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

The program declares a delegate type called StrMod as delegate string StrMod(string str);

StrMod takes one string parameter and returns a string.

In DelegateTest class, three static methods are declared, each with g , ,a single parameter of type string and a return type of string. Thus they match the StrMod delegate.

In Main() a StrMod reference called strOp is created {delegateIn Main(), a StrMod reference called strOp is created. {delegate instantiation} and assigned a reference to ReplaceSpaces(). StrMod strOp = new StrMod (ReplaceSpaces );

Only name is used while passing the function name to the delegate instance, no parameters are specified.

While instantiating a delegate you specify only the name of theWhile instantiating a delegate, you specify only the name of the method to which you want the delegate to refer. Of course, the method signature must match that of the delegate’s declaration.

If it doesn’t, a compile-time error will result.272© http://www.ashishpal.wordpress.com

Page 8: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Next, ReplaceSpaces() is called through the delegate instance strOp, as str = strOp(“This is a test.”);

Because strOp refers to ReplaceSpaces(), ReplaceSpaces() is invoked.

Next, strOp is assigned reference to RemoveSpaces(), and then strOp is called again.strOp = new StrMod ( RemoveSpaces );strOp new StrMod ( RemoveSpaces );str = strOp(“This is a test.”);

Finally, strOp is assigned a reference to reverse() and strOp is y, p g () pcalled. This results in reverse() being invoked.strOp = new StrMod ( reverse );str = strOp(“This is a test.”);

The key point is invocation of strOp results into a call of the method referred to by strOp at the time at which the invocation occurs Thus the method to call is resolved at runtime notoccurs. Thus, the method to call is resolved at runtime, not compile time.

273© http://www.ashishpal.wordpress.com

Page 9: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Use of Delegate – static methods.using System;//delegate declaration

d l t i t O ti (i t i t )delegate int Operation(int x, int y);

Class MathOpr{

public static int Add (int a, int b){ return a+b; }{ return a+b; }public static int Sub (int a, int b){ return a-b; }public static int Mul (int a, int b){ return a*b; }

}}Class Test{

public static void Main(){//delegate instantiationO ti O 1 O ti (M thO Add)Operation Opr1 = new Operation (MathOpr.Add);Operation Opr1 = new Operation (MathOpr.Sub);Operation Opr1 = new Operation (MathOpr.Mul);

//invoking of delegatesint ans1 = Opr1(200 100);int ans1 Opr1(200,100);int ans2 = Opr2(200,100);int ans3 = Opr3(20,10);

Console.WriteLine(“ Addition : “ + ans1);Console.WriteLine(“ Subtraction : “ + ans2);Console.WriteLine(“ Multiplication : “ + ans3);}

} 274© http://www.ashishpal.wordpress.com

Page 10: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Use of Delegate – instance methods.//delegates can refer to instance methods too.using System;

//declaring a delegate type.delegate string StrMod(string str);delegate string StrMod(string str);Class StringOps {

//replaces space with hyphens.public string ReplaceSpaces ( string s ) {public string ReplaceSpaces ( string s ) {Console.WriteLine(“Replacing spaces with hyphens.”);return s.Replace(‘ ‘,’-’);}

//remove spaces.public string RemoveSpaces ( string s ) {string temp = “”;int i;Console.WriteLine(“Removing Spaces.”);for ( i=0; i < s.Length ; i++)if(s[i] != ‘ ‘) temp += s[i];if(s[i] != ‘ ‘) temp += s[i];return temp;}

//reverse a string.public string reverse ( string s ) {public string reverse ( string s ) {string temp = “”;int i, j;Console.WriteLine(“Reversing the string.”); 275© http://www.ashishpal.wordpress.com

Page 11: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

for (j=0 , i = s.Length-1; i>=0; i-- , j++) temp += s[i];

return temp;}

Class DelegateTest {

static void Main() {StringOps so = new StringOps(); // creating an instance of class StringOps

//Initialize a delegateStrMod strOp = so.ReplaceSpaces;string str;

//call methods through the delegates.//call methods through the delegates.str = strOp(“This is a test.”);Console.WriteLine(“Resulting String: “ + str);

strOp = so.RemoveSpaces;str = strOp(“This is a test.”);Console.WriteLine(“Resulting String: “ + str);

strOp = so.reverse;str = strOp(“This is a test.”);Console.WriteLine(“Resulting String: “ + str);

}}

276© http://www.ashishpal.wordpress.com

Page 12: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

The output of this program is:

This program produces the same output as the first one,but in this case the delegate refers to the methods onbut in this case, the delegate refers to the methods on an instance of StringOps class.

Replacing spaces with hyphens.Replacing spaces with hyphens.Resulting String: This-is-a-test.

Removing spaces.Resulting String: Thisisatest.

Reversing the string.Resulting String: .tset a si sihT

277© http://www.ashishpal.wordpress.com

Page 13: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Multicasting / Multicast Delegatesg gOne of the most exciting features of a delegate is it support for multicasting.M lti ti i th bilit t t d i ti li t h i fMulticasting is the ability to create and invocation list, or chain, of methods that will be automatically called when a delegate is invoked.Process:Process:

Instantiate a delegateUse the + or += operator to add methods to the chainU th t t th d f th h iUse the – or -= operator to remove a method from the chain.

If the delegate returns a value, then the value returned by the last method invoked in the list becomes the return value of the entire delegate invocationdelegate invocation.A delegate that makes use of multicasting will often have a voidreturn type.

278© http://www.ashishpal.wordpress.com

Page 14: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Use of Multicast Delegates – Example 1using System;delegate void MultiCDel();

class MD {static p blic oid Hello() {static public void Hello() {Console.WriteLine ( “Hello” ) ;}static public void Show() {Console.WriteLine ( “Hi” ) ;}}

}class Test {

public static void Main() {//delegate instancesMultiCDel M1 = new MultiCDel (MD.Hello); Output:MultiCDel M2 = new MultiCDel (MD.Show);//combine the delegatesMultiCDel M3 = M1 + M2;MultiCDel M4 = M2 + M1;//extracting the delegatesMultiCDel M5 = M3 M2;

Output:

HelloHi

iMultiCDel M5 = M3 - M2;MultiCDel M6 = M4 – M1;//invoking delegatesM3();M4();M5();

HiHello

HelloM5();M6();}

}

Hi

279© http://www.ashishpal.wordpress.com

Page 15: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Use of Multicast Delegates – Example 2

using System;

delegate void StrMod(ref string str);Cl M ltiC tDClass MultiCastDemo {

//replaces space with hyphens.static void ReplaceSpaces (ref string s ) {Console WriteLine(“Replacing spaces with hyphens ”);Console.WriteLine( Replacing spaces with hyphens. );s = s.Replace(‘ ‘,’-’);}

//remove spaces.static void RemoveSpaces (ref string s ) {string temp = “”;int i;Console.WriteLine(“Removing Spaces.”);for ( i=0; i < s.Length ; i++)if(s[i] != ‘ ‘) temp += s[i];s = temp;s = temp;}

//reverse a string.static void reverse (ref string s ) {string temp = “”;string temp ;int i, j;Console.WriteLine(“Reversing the string.”);

280© http://www.ashishpal.wordpress.com

Page 16: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

for (j=0 , i = s.Length-1; i>=0; i-- , j++) temp += s[i];

s = temp;}}

static void Main() {

//Construct delegates.StrMod strOp;StrMod replaceSp = ReplaceSpaces;StrMod removeSp = RemoveSpaces;StrMod reverseStr = reverse;string str = “This is a test.”;

//set up Multicast.strOp = replaceSp;strOp += reverseStr;

//Call Multicast.strOp(ref str);Console.WriteLine(“Resulting String: “ + str);

//remove replace and add remove.strOp -= replaceSp;t O SstrOp += removeSp;

str = “This is a test.”; // reset string

//call Multicast.strOp (ref str);strOp (ref str);Console.WriteLine(“Resulting String: “ + str);}

} 281© http://www.ashishpal.wordpress.com

Page 17: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

The output of this program is:The output of this program is:

Replacing spaces with hyphens.Reversing the String.Resulting String: .tset a si sihT

Reversing the String.Removing spaces.Resulting String: .tsetasisihT

282© http://www.ashishpal.wordpress.com

Page 18: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

System.Delegate

All delegates are classes that are implicitly derived fromAll delegates are classes that are implicitly derived from System.Delegate.

Why Delegates?First, delegates support events.Second, delegates give programs a way to execute methods at runtime without having to know precisely what thoseat runtime without having to know precisely what those methods are at compile time.

283© http://www.ashishpal.wordpress.com

Page 19: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

P ti l t t l k dPartial contextual keywordStarted with C# 2 0Started with C# 2.0A class, structure or interface definition can be broken into two or more pieces, with each piece residing in separate files.When program is compiled the pieces are unitedWhen program is compiled, the pieces are united.

partial class XY {public XY(int a, int b) {

X=a;

partial class XY {public int X {

get;

partial class XY {public int Y {

get;X a;Y=b;}} xy1.cs

get;set;

}} xy2.cs

get;set;

}} xy3.cs

using System; // demonstrating the use of partial class definitions

class Test {

static void Main() {

XY XY(1 2)XY xy = new XY(1,2);

Console.WriteLine(xy.X + “,” + xy.Y); } } to compile Test: csc test.cs xy1.cs xy2.cs xy3.cs284© http://www.ashishpal.wordpress.com

Page 20: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

P ti l th dPartial methodsStarted with C# 3 0 creating Partial MethodsStarted with C# 3.0, creating Partial Methods.Declaration in one part & implementation in another.Key aspect of a partial method is that the implementation is not requiredrequired.When a partial method is not implemented by another part of the class or structure, then all calls to the partial method are silently ignoredignored.

//Demonstrate a partial method.

using system;

partial class XY (int a, int b) {partial class XY (int a, int b) {

X=a;

Y=b;

}

//Declare a partial method.

285© http://www.ashishpal.wordpress.com

Page 21: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

partial void Show();

}}

partial class XY {

public int X{ get; set; }

//Implement a partial method.p p

partial void Show()

{ Console.WriteLine(“{0},{1}”, X,Y};}

}

partial class XY {

public int Y {get; set;}

//call a partial method//call a partial method.

public void ShowXY()

{ Show();}

}}

class Test {

static void Main() {

XY xy = new XY(1,2);

xy.ShowXY();

}} 286© http://www.ashishpal.wordpress.com

Page 22: Dl tDelegates - ashishpal.files.wordpress.com · Dl tDelegates zA delegate is an object that can refer to a method.A delegate is an object that can refer to a method. zCreating delegate,

Notice that the show() is declared in one part of XY and implemented by another part. The implementation displays the values of X & Y.This means that when Show() is called by ShowXY(), the call has effect, and it will, indeed, display X & Y. Comment the implementation of Show(), then calling Show() inside ShowXY() does nothing.Restrictions on Partial Methods:

They must return void.They can not have access modifiers.They can not be virtual.yThey can not use OUT parameters.

287© http://www.ashishpal.wordpress.com