|
-
Jan 17th, 2007, 05:42 AM
#1
Thread Starter
Addicted Member
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?
-
Jan 17th, 2007, 09:26 AM
#2
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|