I have a few suggestions on how you can go about "mastering" delegates and events.
Consider this delegate example:
public delegate string Del_ReturnSumAsString(int x, int y);
1. start with focusing on what a "delegate" is:
a. a "signature," or "blueprint," or "template" for a method
b. that must specify a return Type (or "void"), and that must specify a list of parameters in the same way a method/function specifies them in .NET.
... in the example above you describe the signature of a method that will return an object of Type string, and that takes two objects of Type int as parameters ...
2. then focus on how you create an "instance" of a delegate:
a. just like you declare instances of variables:
public Del_ReturnSumAsString ReturnSumAsString;
...You have now declared 'ReturnSumAsString as a special type of instance: perhaps think of it as a "place-holder," or "container" for a method definition that exactly matches the delegate's signature.
3. now you can "insert" into the instance of the delegate a pointer to a method: so let's define a method, and insert it:
public string TwoIntsToString(int x, int y)
{
return (x + y).ToString();
}
So now we have the delegate, the instance of the delegate, and method declared ready-to-be-assigned to the instance of the delegate.
How do we assign our method to the instance of the delegate ?
We have to do this in code that is executed at run-time. Let's use a Form's Load event as an example:
private void Form1_Load(object sender, EventArgs e)
{
ReturnSumAsString = TwoIntsToString;
}
And, now, we can invoke the instance of the delegate as if we had executed the function 'TwoIntsToString:
string result = ReturnSumAsString (3, 4);
At this point, I hope you are wondering why we have gone to so much trouble to create such an "indirect" way of calling the function 'TwoIntsToString.
We'll conclude this little journey by saying that this "indirection" we have created is:
a "de-coupling" of the name of a method and its executable code.
But, that's just the beginning of the journey ! However, I guarantee you, that, if you understand what a delegate is, as presented here, you will have a foundation to build on, as you go on to consider how delegates relate to events, and their other uses ... or your money back :)
"rahi gulzar to phool khilenge" Kabir