Prev | Current Page 212 | Next

Jon Skeet

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

You could have an interface like this:
public interface IStorageLocation
{
Stream OpenForRead();
...
IEnumerable GetSublocations();
}
That all seems reasonable and easy to implement. The problem comes when your
implementation (FabulousStorageLocation for instance) stores its list of sublocations
for any particular location as List. You might
expect to be able to either return the list reference directly, or possibly call AsRead-
Only to avoid clients tampering with your list, and return the result??”but that would
be an implementation of IEnumerable instead of an
IEnumerable.
Here are some options:
?–  Make your list a List instead. This is likely to mean you need
to cast every time you fetch an entry in order to get at your implementationspecific
behavior. You might as well not be using generics in the first place.
?–  Implement GetSublocations using the funky new iteration features of C# 2, as
described in chapter 6. That happens to work in this example, because the
interface uses IEnumerable. It wouldn??™t work if we had to
return an IList instead. It also requires each implementation
to have the same kind of code. It??™s only a few lines, but it??™s still inelegant.
?–  Create a new copy of the list, this time as List.


Pages:
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224