A.10. Chapter 12
A.10.1. Exercise 1 Solution
The major advantage of generics is that they provide data flexibility without sacrificing strong type checking. Another advantage is that generics can avoid the overhead associated with boxing and unboxing the data. It's not uncommon for generics to provide a 100% performance increase over code that must exercise the boxing-unboxing process. Finally, the absence of generics almost always means that your code must use a lot of casts to accommodate more flexible coding practices. The "cast hassle" is avoided with generics.
A.10.2. Exercise 2 Solution
The first thing you would do is modify the ShowData() method along these lines:
private void ShowDataGeneric<T>(T[] val)
{
int i;
for (i = 0; i < t.Length; i++)
{
if (whichListbox == SORTED)
lstSorted.Items.Add(val[i].ToString());
else
lstUnsorted.Items.Add(val[i].ToString());
}
}
This enables you to pass in the data array that needs to be displayed. Note the use of the generic type specifier in the method's signature. Next, you would need to modify the code in the switch statements where ShowData() is used. For example, in btnSort_Click() event the code
case INTEGER: // Integer
clsQuickSort<int> iSort = new clsQuickSort<int>(iData);
iSort.Sort();
break;
needs to add a call to the new generic method and remove the old call to ShowData(). The next code for the integer data type would be as follows:
case INTEGER: // Integer clsQuickSort<int> iSort = new clsQuickSort<int>(iData); iSort.Sort(); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access