Ali
Ali

Reputation: 5426

What is the generic alternative of Array?

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?

Upvotes: 3

Views: 7539

Answers (5)

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

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>(myIntArray)

Upvotes: 4

Damien McGivern
Damien McGivern

Reputation: 4004

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.

Upvotes: 0

JaredPar
JaredPar

Reputation: 755397

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;
}

Upvotes: 1

Richard
Richard

Reputation: 109140

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

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503310

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.

Upvotes: 6

Related Questions