views:

625

answers:

5

In C# some collections such as ArrayList and HashTable have generic alternatives which are List<T> and Dictionary<TKey, TValue>.

Does Array also have a generic alternative?

+6  A: 

No - just use a strongly typed array, e.g. int[]. It's relatively rare to use a "weakly typed" Array in the first place - in fact, I don't believe you can really create one. Every Array is really a strongly-typed one, even if you don't refer to it that way.

Jon Skeet
I'd say T[] is the generic alternative of Array, except it existed before generics.
configurator
how about arrays with reference type elements? you could have an object array or animal array..
Gulzar
That's just string[] or Animal[]. I only picked int[] as a random example - there's nothing important about the int part really.
Jon Skeet
got it. now i see what you meant..
Gulzar
+4  A: 

Array has always been, with special compiler support, somewhat generic.

E.g. System.Array allows objects in, but an int[] does not.

Richard
+1  A: 

Expanding on Jon's answer

Arrays have no generic alternative because it's perfectly fine to have a generic array.

public static T[] CreateArray<T>(T item1, T item2) {
   T[] array = new T[2];
   array[0] = item1;
   array[1] = item2;
   return array;
}
JaredPar
+1  A: 

If you're looking for the generic collection type that most closely resembles an array, then you probably want a List<T>. But it's not really the same thing.

To expand on what others have said: the point of having generic types is so that a programmer can then use type-specific instances of those generic types, based on the needs of the current program. Arrays are already type-specific. You can always just take a T[].

For example, look at this simple function definition:

void SomeFunction(int[] x)

You could also think of it like this:

void SomeFunction<T>(T[] x)

where the programmer just chose to call it with an int for the type parameter:

SomeFunction<int>(T[] x)
Joel Coehoorn
Can you have a two or more dimensional List<T> like you can have in Array?
Ali
You can have List<List<T>>, but like I said before: it's not really the same thing. And if you're using 2-D arrays that often you're probably doing something else wrong.
Joel Coehoorn
See this (written by one of the C# language designers): http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
Joel Coehoorn
A: 

There is no need for a generic alternative as when you define an array you state the type of the array. All the classes you mentioned are simple collection classes. An aray is a totally different data structure.

Damien McGivern
Can you please explain the difference?
Ali