Im trying to get my head around using Delegates. Can someone give me a scenario where i would use these.
Thanks
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
DavePosted Aug 3, 2010, 11:32 AM
Alexandru LazarPosted Aug 3, 2010, 10:00 AM
In the following example the actual course of action is decided by the user.
You can also see from this example that you can think of methods as objects and you can think of delegates as classes. You can actually pass methods as parameters:
DavePosted Aug 3, 2010, 7:41 AM
using System;
using System.Collections.Generic;
using System.Text;
namespace DelegateEX
{
public delegate void mydele(int x, int y);
class A
{
public void add(int x, int y)
{
Console.WriteLine("The Sum is " + (x + y));
}
public void sub(int x, int y)
{
Console.WriteLine("The Difference is " + (x - y));
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
A obj = new A();
//make an object of class A
mydele m = new mydele(obj.add);
m(10, 20);
mydele m1 = new mydele(obj.sub);
m1(10, 20);
}
}
}
Alexandru LazarPosted Aug 3, 2010, 6:57 AM
You have two segments of code that you want to keep separate. The first segment decides which method (of a set) must be executed and the second segment executes the chosen method.
If all the methods in the set have the same return type and parameters:
you can create a delegate
In one part of your code you decide what method you must use (based on user input):
Mamta MPosted Aug 3, 2010, 6:47 AM
Consider an example. Lets say a delegate says to itself I am supposed to point to a method returning an int and accepting an int. At runtime, the ambiguity is resolved, and the delegate makes the (astonishing?!) discovery that the method it is pointing to is Calc.
Hope this makes it a little clear.
DavePosted Aug 3, 2010, 6:39 AM
How would it not know what it is at runtime.
sorry if this sounds a bit dumb, just trying to get it straight in my head.
Mamta MPosted Aug 3, 2010, 6:03 AM
btn_Click += delegate_name;
where delegate_name points to your user-defined method that will act as the event handler.
Of course, there are plenty of other uses of delegates but this is a practical easy to understand example that I have given you.
-Mamta