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 ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.