Todd Moses
Todd Moses

Reputation: 11029

How to pass a generic array in C#?

I need to pass an array to a function in C# where the array may be a string[], int[], or double[] and may be 1 to multiple dimensions.

Reasoning:

I am needing to pass an array to a function to calculate its length, similar to:

public int getLength(array[] someArray, int dimension)
{
   if(dimension > 0) //get length of dimension 
     return someArray.getLength(dimension);
   else //get length of entire array
     return someArray.Length;
}

Question:

How can I pass a generic array?

Or

Is there a better way to do this - say convert the array to a List?

Upvotes: 2

Views: 4136

Answers (2)

Mark Avenius
Mark Avenius

Reputation: 13947

If you want List-like properties, you can also use ArrayList, which holds an arbitrary number of objects

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062755

For the purpose you cite, just pass Array someArray - that should be fine, and covers any number of dimensions. For a vector (a 1-dimensional, 0-based array), you can use generics (GetLength<T>(T[] someArray)) - but that seems pointless when for a vector .Length is more convenient.

But for an unknown number of dimensions (or for a non-vector single-dimensional array), you are limited to Array.

Upvotes: 4

Related Questions