20.2. Motivation for Generic Methods

Overloaded methods are often used to perform similar operations on different types of data. To understand the motivation for generic methods, let’s begin with an example (Fig. 20.1) that contains three overloaded DisplayArray methods (lines 23–29, lines 32–38 and lines 41–47). These methods display the elements of an int array, a double array and a char array, respectively. Soon, we’ll reimplement this program more concisely and elegantly using a single generic method.

 1   // Fig. 20.1: OverloadedMethods.cs  2   // Using overloaded methods to display arrays of different types.  3   using System;  4  5   class OverloadedMethods  6   {  7      static void Main( string[] args ...

Get Visual C#® 2012: How to Program, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.