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?
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?
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.
Array has always been, with special compiler support, somewhat generic.
E.g. System.Array allows objects in, but an int[] does not.
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;
}
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)
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.