I understand the benefit of the delegate but i am not find example to convinced me for the usage.
what i understnd is "you need your program to call a method, but you can't know what that method will be until run-time".
when i see all example i am find that i doesn't need for delegate like this example
because when I take object from the class I will determine what method need to be invoked or i can make condition.Code: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; } 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); //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(); } } }




Reply With Quote