Although the array version will compile, it will fail at execution time. This was
deemed by the designers of generics to be worse than failing at compile time, which is
reasonable??”the whole point of static typing is to find out about errors before the code
ever gets run.
NOTE So why are arrays covariant? Having answered the question about why
generics are invariant, the next obvious step is to question why arrays are
covariant. According to the Common Language Infrastructure Annotated
Standard (Addison-Wesley Professional, 2003), for the first edition the
designers wished to reach as broad an audience as possible, which included
being able to run code compiled from Java source. In other words, .NET has
covariant arrays because Java has covariant arrays??”despite this being a
known ???wart??? in Java.
So, that??™s why things are the way they are??”but why should you care, and how can you
get around the restriction?
Valid (at compile-time):
Animal[] animals = new Cat[5];
animals[0] = new Animal();
Invalid:
List
animals=new List();
animals.Add(new Animal());
104 CHAPTER 3 Parameterized typing with generics
WHERE COVARIANCE WOULD BE USEFUL
Suppose you are implementing a platform-agnostic storage system,11 which could run
across WebDAV, NFS, Samba, NTFS, ReiserFS, files in a database, you name it. You may
have the idea of storage locations, which may contain sublocations (think of directories
containing files and more directories, for instance).
Pages:
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223