A delegate is like a strongly-typed function pointer :). Did that help?
Basically, it's a way you can treat code as data -- store it, pass it
around, and call it when you want.
Every event takes a delegate, for instance:
private myMethod(object sender, EventArgs e) {
MessageBox.Show("hi!");
}
// in some other place:
myEventHandler = new EventHandler(myMethod);
someButton.Click += myEventHandler;
In this case, we create a new EventHandler delegate, and attach it to the
Click event. Then, when the event is raised, it invokes all the delegates
that have been attached.
Another use would be for benchmarking. For a benchmark, I might want to find
out how long method X and Y take. The basic code would be:
long start = QueryPerformanceCounter();
doSomeCode(iterations);
long end = QueryPerformanceCounter();
long time = end-start;
Console.WriteLine("SomeMethod took {0} seconds.", time /
QueryPerformanceFrequency());
And it might have other things like garbage collection and so on. If I want
to test 10 methods, I need to replicate the code 10 times. With a delegate,
I could make that code into a method that takes a delegate.
public delegate void BenchmarkDelegate(int iterations);
public doBenchmark(BenchmarkDelgate methodToTest) {
// timing code
methodToTest(iterations);
// timing code
}
-mike
MVP
"juan" <ic***@hotmail.com> wrote in message
news:ec*************@TK2MSFTNGP12.phx.gbl...
hi
i was going thru some samples and i couldnt understand what this line
means
public delegate void DataListItemEventHandler(object sender,
DataListItemEventArgs args);
what is a delegate and what are delegates used for?
thnx