2

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I was needing. I did not know that Array actually existed. Thanks.
@Todd - it is the base-class for vectors, i.e. int[] : Array
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.