Prev | Current Page 185 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

..
List
ref
6
byte[] ArrayList
ref
6
ref
ref
ref
ref
ref
ref
...
object[]
5
3
15
10
12
13
Boxed
bytes
count count
elements elements
Figure 3.3 Visual demonstration of why List takes up a lot less space than ArrayList
when storing value types
90 CHAPTER 3 Parameterized typing with generics
3.4.3 Generic iteration
One of the most common operations you??™ll want to perform on a collection (usually
an array or a list) is to iterate through all its elements. The simplest way of doing that
is usually to use the foreach statement. In C# 1 this relied on the collection either
implementing the System.Collections.IEnumerable interface or having a similar
GetEnumerator() method that returned a type with a suitable MoveNext() method
and Current property. The Current property didn??™t have to be of type object??”and
that was the whole point of having these extra rules, which look odd on first sight. Yes,
even in C# 1 you could avoid boxing and unboxing during iteration if you had a
custom-made enumeration type.
C# 2 makes this somewhat easier, as the rules for the foreach statement have been
extended to also use the System.Collections.Generic.IEnumerable interface
along with its partner, IEnumerator. These are simply the generic equivalents of
the old enumeration interfaces, and they??™re used in preference to the nongeneric versions.


Pages:
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197