www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# Delegates Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Delegates are similar to C function pointers. C / C++ function pointers lack instance-based knowledge, whereas C# delegate are event based. Delegates are reference types which allow indirect calls to methods. A delegate instance holds references to some number of methods, and when the delegate is invoked all of these methods are called. The usefulness of delegates lies in the fact that the functions which invoke them are blind to the underlying methods they thereby cause to run.

An example of delegates is shown below:

public delegate void Print (String s);
public void realMethod (String myString)
// method code

public void realMethod2 (String myString)
// method code

public void realMethod3 (String myString1, String myString 2)
// method code

Another method in the class could then instantiate the 'Print' delegate in the following way, so that it holds a reference to 'realMethod':

Print delegateVariable = new Print(realMethod);

Then invoking the realMethod() through delegateVariable is pretty straight forward:


To add additional method to the delegate we use the += operator as demonstrated below:

delegateVariable += realMethod2;

An important thing to remember is that whatever method you add to a delegate its signature must match to the delegate type. In the above example the Print delegate can take any method that takes a single string as an argument. If we try to add a method that has a different signature, a compile time error is generated. For example the following code will not compile:

delegateVariable += realMethod3; // compile time error!
Next >>> Lesson No. 23: C# Events

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.