0

I have an array with Length = 3 and with values, for example {1,2,3}. I need to dynamically resize it.

I know that I can use List or Array.Resize(). But I need to know how to implement my own resize method?

5
  • 1
    A problem with this is that any references to the old array will not change to reference the new array. Commented Sep 29, 2015 at 17:48
  • msdn.microsoft.com/en-us/library/bb348051(v=vs.110).aspx You can look at the reference source for that and see how they did it, but it should be pretty obvious. Commented Sep 29, 2015 at 17:48
  • 1
    basically, create a new array Commented Sep 29, 2015 at 17:53
  • 2
    referencesource.microsoft.com/#mscorlib/system/… Commented Sep 29, 2015 at 17:54
  • Why do you need to implement your own resize method? Commented Sep 29, 2015 at 18:16

5 Answers 5

5

You can try the following code. Create new array with new size and copy the old array data to the newly created array.

public static Array ResizeArray (Array oldArray, int newSize)
{
    int oldSize = oldArray.Length;
    Type elementType = oldArray.GetType().GetElementType();
    Array newArray = Array.CreateInstance(elementType,newSize);
    int preserveLength = System.Math.Min(oldSize,newSize);
    
    if (preserveLength > 0)
    {
        Array.Copy (oldArray,newArray,preserveLength);
    }

    return newArray;
}
Sign up to request clarification or add additional context in comments.

2 Comments

The OP does not want using Array.Resize method.
@FelipeOriani I fixed it.
1

If this is just for practice then do it. but i suggest you use .Net Array.Resize() if you want to use it in your code. usually .Net libraries are best implemented and optimized.

Any way...you can do it with generic method

private static void Resize<T>(ref T[] array,int size)
{
    T[] token = array.Take(size).ToArray(); // attempt to take first n elements
    T[] temp = new T[size]; // create new reference
    token.CopyTo(temp, 0); // copy array contents to new array
    array = temp; // change reference
}

Note that you cannot do this without parameter ref. (The other way is to return array of course)

You may think arrays are passed by reference. thats true. But the references it self are passed by value. so whenever you try to change the reference it does not refer to the original array anymore. you can only change the contents. To make this possible you have to use ref to directly pass the reference into method.

About the code:

{1,2,3} if you resize it to 2 obviously it will remove the last parameter. so you will have {1,2}

if you resize it to 4 then it will give the array with new default values. either null for reference types or 0 for value types (false for Boolean type). here you will have {1,2,3,0}

int[] array = new[] {1, 2, 3};
Resize(ref array,4);
Console.WriteLine(array.Length); // outputs 4

Comments

0

Well, you may look on Array.Resize source code before making your own implementation =) http://referencesource.microsoft.com/#mscorlib/system/array.cs,71074deaf111c4e3

Comments

0

If you want to resize the array use the build in method Array.Resize().It will be easier and faster.

If you need a dynamically sized data structure, use List for that. You can always do array.ToList() -> fill the list and do .ToArray() later.

Comments

-1

Make an array of the new desired size, copy all items over. Make the variable that referenced your old array reference the new one.

Code from MSDN:

public static void Resize<T>(ref T[] array, int newSize) {
    if (newSize < 0) {
        throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
        Contract.Ensures(Contract.ValueAtReturn(out array) != null);
        Contract.Ensures(Contract.ValueAtReturn(out array).Length == newSize);
        Contract.EndContractBlock();

        T[] larray = array;                
        if (larray == null) {
            array = new T[newSize];
            return;
        }

        if (larray.Length != newSize) {
            T[] newArray = new T[newSize];
            Array.Copy(larray, 0, newArray, 0,  larray.Length > newSize? newSize : larray.Length);
            array = newArray;
        }
    }
}

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.