Reset length array in C#

hi all,

i am still new in C#,
In you can use redim to reset the length of an array, but in C# how i can reset the length of an array
Who is Participating?
crysallusConnect With a Mentor Commented:
Array.Resize(myArray, newLength);
crysallusConnect With a Mentor Commented:

Array.Resize(ref myArray, newLength);

Open in new window

MKItaniAuthor Commented:
thsnk  u verry much  crysallus but how i can use array.resize in case i have a array of two or three dimensials like:
A[2][3] or B[2][3][4]

i am waiting for your response.
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

StephanConnect With a Mentor Lead Software EngineerCommented:
There is no real function available within the .net framework.

You could create your own resize function in order to fix this.
MKItaniAuthor Commented:
thank u stephanonline but this reset the length of a string of array.
Dear all,
 what i want is function that can reset a multidimension of any type of array?

Waiting for you response.
StephanConnect With a Mentor Lead Software EngineerCommented:
the string type is just an example.

When you want to use any type, you can do the following:

private void ResizeArray<T>(ref T[,] original, int cols, int rows) where T : class
    //create a new 2 dimensional array with
    //the size we want
    T[,] newArray = new T[rows, cols];
    //copy the contents of the old array to the new one
    Array.Copy(original, newArray, original.Length);
    //set the original to the new array
    original = newArray;

Open in new window

and to call the function, you can do as follows:

ResizeArray<int>(list, 2, 10);

If you have three dimensional, you need to create the function that accept this.
There is no other way.
crysallusConnect With a Mentor Commented:
Yeah, ditto what stephanonline said about handling arrays of more than one dimension.

Though of course in C#, T[,] is different to T[][]. See if you're not sure on the difference. You may need to change stephanonline's code to T[][] if that's the type of arrays you are using.

If you're doing this often, then you'd probably be best using some collection class like List<T>, and have List's of Lists, which you can add elements to at will. Resizing arrays is not something that is normally done too often, hence the lack of .NET functions to do it. The C# way would be to use a collection class like List<T> or ArrayList instead.
MKItaniAuthor Commented:
not accurate
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.