Chapter 12

Generics

What you will learn in this chapter:

  • Generics
  • Advantages generics offer
  • Boxing and unboxing
  • Run time type checking
  • Interfaces
  • Recursion

wrox.com code downloads for this chapter

You can find the wrox.com code downloads for this chapter at www.wrox.com/remtitle.cgi?isbn=9781118336922 on the Download Code tab. The code in the Chapter12 folder is individually named according to the names throughout the chapter.

This chapter discusses generics, a feature that has been a part of C# since its 2005 release. Generics have the potential to save you a ton of programming effort.

Generics offer you a way to stretch your programming time in ways that just make sense. In this chapter you examine what this relatively new OOP feature has to offer.

What Are Generics?

The best way to appreciate what generics bring to the programming table is with an example. Sorting data is a common programming problem. I once was interviewed for a consulting job and part of the interview was a programming test in which I was expected to generate a series of random numbers, display them in a listbox, sort them into ascending order, and redisplay them in a second listbox. The interviewers weren't happy when I bypassed writing my own sort routine and simply turned on the Sorted property in the second listbox. Moral: Know your toolkit. But suppose you have to sort a series of integer data into ascending order and you can't use the listbox trick. How would you write the solution?

As part of your ...

Get Beginning Object-Oriented Programming with C# 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.