Results 1 to 2 of 2

Thread: purpose of delegates

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2005
    Posts
    150

    purpose of delegates

    are delegates just a means of ensuring the correct amount of paramters and the correct types are passed to a method at compile time rather than an error been thrown at runtime if delegates were not used?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: purpose of delegates

    That's completely not the purpose. A delegate is an object that contains a reference to a method. You can pass that object around wherever you like and when you call its Invoke method the method it refers to will be executed. An example of how delegates are used is in raising and handling events. When you register a handler for an event you are actually providing the object that will raise the event with a reference to the method that will handle the event.

    Let's say that object A raises event E. Object B has a method M that will handle that event. Now, object A has no reference to object B, so how is object A to call method M when it raises event E? It can't do it directly because it would need reference to object B to do so. The answer is to use a delegate. Object B passes a reference to method M to object A, which wraps it in delegate D. Now, when object A raises event E it simply invokes delegate D. Delegate D contains a reference to method M, so method M gets executed without object A requiring a direct reference to object B.

    That's just one use for delegates. The other most common use would be to cross a thread boundary in order to access a control on the UI thread from a worker thread.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width