Chapter 6: Delegates and Attributes

Part II
Advanced C#
Chapter 6
Delegates and Attributes
  • Using Delegates
  • Handling Events
  • Working with Attributes

If you have a background in C or C++, the material in Part I of this book has probably had a familiar feel. Many of the C# language features discussed thus far are similar to features that are available in C or C++. This chapter introduces three C# features that may be new to you: delegates, events, and attributes.

Delegates are the C# way to enlist methods contained in other classes. As you’ll see, a delegate is similar to a function pointer or callback function in C or C++, but it’s type-safe and more flexible. Delegates also work well with the C# language and can target both static and non-static methods—something that’s difficult to do in C++. In this chapter, we’ll examine how events extend delegates to provide a well-defined idiom for client subscription to event notifications.

This chapter will also cover attributes, how they’re used to declaratively add functionality to your code, and how you can create your own attributes. This discussion of attributes will include reflection, a common language run­time feature that enables you to inspect and extract information about types at runtime.



Part III: Programming Windows Forms