Summary

  • Modern GUIs rely on events generated by the user or by the system to know what action to take.

  • A delegate is a reference to a method of a particular signature and return type.

  • Delegates allow polymorphism by encapsulating a method that matches the delegate signature. The method encapsulated by the delegate is decided at runtime.

  • An object can publish a series of events to which other classes can subscribe. The publishing class defines a delegate and an event based on that delegate. The subscribing class creates a method that matches the signature of the delegate, and registers that method with an instance of the delegate.

  • In .NET, all event handlers return void, and take two parameters. The first parameter is of type object and is the object that raises the event; the second argument is an object of type EventArgs or of a type derived from EventArgs, which may contain useful information about the event.

  • Event handlers subscribe to delegates using the += operator and unsubscribe using the -= operator.

  • The keyword event ensures that event handlers can only subscribe or unsubscribe to the event. Handlers can’t call the delegate event directly, nor can they access its internal members.

  • Instead of passing a method name to a delegate, you can pass a block of code, using the keyword delegate. This creates an anonymous method.

  • A lambda expression is an expression using the operator => that returns an unnamed method. Lambda expressions are similar to anonymous methods, but aren’t restricted to being used as delegates.

This chapter introduced a lot of new ideas, and possibly made you think differently about how methods work. A lot of what delegates do can also be done with interfaces, but as you’ve seen, delegates really come into their own as event handlers. Throughout this chapter, we’ve emphasized that one of the main functions of event handlers is to work with a GUI interface, like Windows, but we haven’t shown you how to do that yet. In the next chapter, you’re finally going to break out of the console window and see how to make some Windows applications. This is the one you’ve been waiting for.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset