Introduction


Delegates contain all that is needed to allow a method, with a specific signature and return type, to be invoked by your code. A delegate can be passed to methods and a reference to it can be stored in a structure or class. A delegate is used when, at design time, you do not know which method you need to call and the information to determine this is available only at runtime.

Another scenario is when the code calling a method is being developed independently of the code that will supply the method to be called. The classic example is a Windows Forms control. If you create a control, you are unlikely to know what method should be called in the application when the control raises an event, so you must provide a delegate to allow the application to hook up a handler to the event. When other developers use your control, they will typically decide when they are adding the control (through the designer or programmatically) and which method should be called to handle the event published by the control. (For example, it's common to connect a Button's click handler to a delegate at design time.)

Anonymous methods are delegates without the full delegate syntax. They are a feature of the C# compiler and not a CLR type. An anonymous method is ultimately created as a delegate instance by the compiler, but the syntax for declaring an anonymous method can be more concise than declaring a regular delegate. Anonymous methods also permit you to capture variables in the same scope and use programming techniques such as closures and functors (explained later in this chapter).

This chapter's recipes make use of delegates, events, and anonymous methods. Among other topics, these recipes cover:

  • Handling each method invoked in a multicast delegate separately

  • Synchronous delegate invocation versus asynchronous delegate invocation

  • Enhancing an existing class with events

  • Various uses of anonymous methods, closures, and functors

If you are not familiar with delegates, events, or anonymous methods, you should read the MSDN documentation on these topics. There are also good tutorials and example code showing you how to set up and use them in a basic fashion.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net