Delegates With Examples in C#
Simple Delegates With Examples.
Delegates have the following properties:
- Delegates are similar to C++ function pointers, but are type safe.
- Delegates allow methods to be passed as parameters.
- Delegates can be used to define callback methods.
- Delegates can be chained together; for example, multiple methods can be called on a single event.
- Methods don't need to match the delegate signature exactly.
- Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that can call the referenced method, without having to know at compile time which method will be invoked.
- An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
Example 1
using System; namespace Delegates_CSharp { class Program { // declare delegate public delegate void Print(int value); static void Main(string[] args) { // Print delegate points to PrintNumber Print printDel; printDel = PrintNumber; printDel(100000); printDel(200); // Print delegate points to PrintMoney printDel = PrintMoney; printDel(10000); printDel(200); Console.ReadKey(); } public static void PrintNumber(int num) { Console.WriteLine("Number: {0,-12:N0}", num); } public static void PrintMoney(int money) { Console.WriteLine("Money: {0:C}", money); } } }
Example 2
using System; delegate int NumberChanger(int n); namespace MulticastDelegate_CSharp { class Program { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger nc; NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); nc = nc1; nc += nc2; //calling multicast nc(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } }
Comments
Post a Comment