Next, we see the casts in the Compare method. Casts are a way of
telling the compiler that we know more information than it does??”and that usually
means there??™s a chance we??™re wrong. If the ArrayList we returned from GetSample-
Products had contained a string, that??™s where the code would go bang??”where the
comparison tries to cast the string to a Product.
We??™ve also got a cast in the code that displays the sorted list. It??™s not obvious,
because the compiler puts it in automatically, but the foreach loop implicitly casts
each element of the list to Product. Again, that??™s a cast we??™d ideally like to get rid of,
and once more generics come to the rescue in C# 2. Listing 1.5 shows the earlier code
with the use of generics as the only change.
class ProductNameComparer : IComparer
{
public int Compare(Product first, Product second)
{
return first.Name.CompareTo(second.Name);
}
}
...
List products = Product.GetSampleProducts();
products.Sort(new ProductNameComparer());
foreach (Product product in products)
{
Console.WriteLine(product);
}
The code for the comparer in listing 1.5 is simpler because we??™re given products to
start with. No casting necessary. Similarly, the invisible cast in the foreach loop is
gone. It??™s hard to tell the difference, given that it??™s invisible, but it really is gone. Honest.
Pages:
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53