Delegates

P

Pablo Salazar

Hi people.
I found a book, it talked about oop, in a chapter i found a topic called
"DELEGATES", I read it , but I didn't Understand.
Somebody can tell me where I can find a tutorial or book that explain
delegates in a easy way.

Thanks!.
Pablo Salazar.
 
G

Gary Morris

Welcome to the club!

I struggled with the concept of delegates for weeks before it finally
sunk in. What I had to do was to just sit down and try to write some
kind of program ON MY OWN that used delegates, even if the app
wasn't particularly useful. One day, I finally did it! Once you actually
write an app that does something with delegates, it will be so much
clearer.

There's not an easy way to explain it, that's why it's so much better
to actually do it. What I did was to define a delegate like:

private delegate void myDelegate(string sInput);

All that does is give you a pointer or template of sorts, so that you
can then declare a method with the same signature like:

void CallDelegate1(string sIn)
{
if(some condition based on sIn)
something happens;
else
somthing else happens;
}

At that point, it really makes NO difference what the method does,
which is the beauty of the whole thing. I could write a long and
complicated method that does anything, as long as the declaration
returns void and has a string parameter.

Now, you just need to use it somewhere, like another method:

void UseMyDelegate()
{
myDelegate del1 = new myDelegate(CallDelegate1);
del1("some string");
}

I then proceeded to create another method that matched the
delegate signature, and I made a simple form to try it out. One
button created a method like the above that used the first
method, and another used the same delegate to point to a
different method that matched the signature. Play with it some
and you might "just get it" like I did.

That may or may not help, but should give you something to think
about anyway. I was quite excited when I finally realized how
powerful this concept is. Now I just need to learn how to use
reflection and I'll be able to do some things that I've always wanted
to be able to do, now that I understand delegates a little (LOT)
better!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top