CSharp code equivalent to VB ReDim Preserve

July 7, 2013 § 2 Comments


Resizing arrays while preserving the existing contents is easily done in VB using ReDim Preserve.  In C#, you have other alternatives:

  • Use one of the existing .NET collections, such as ArrayList or the generic List, that handle dynamic resizing automatically.
  • If the array has only one dimension and you’re using C# 2005 or later, then you can use the Array.Resize method.
  • Code the same sort of logic that VB executes for a ReDim Preserve:

VB:
Dim YourArray() As Integer

ReDim Preserve YourArray(i)

C#:
int[] YourArray;

int[] temp = new int[i + 1];
if (YourArray != null)
Array.Copy(YourArray, temp, Math.Min(YourArray.Length, temp.Length));
YourArray = temp;

Here is the complete code of this example:

IncreaseArraySizeAtRuntime.cs Class:

public class IncreaseArraySizeAtRuntime

{

int arrSizeAtRuntime = 0;

int[] arrayDemo = new int[5];

public IncreaseArraySizeAtRuntime()

{

FillArray();

}

public IncreaseArraySizeAtRuntime(int arrSize)

{

this.arrSizeAtRuntime = arrSize;

int[] tempArray = new int[arrSizeAtRuntime];

if (arrayDemo != null)

Array.Copy(arrayDemo, tempArray, Math.Min(arrayDemo.Length, tempArray.Length));

arrayDemo = tempArray;

FillArray();

}

private void FillArray()

{

for (int a = 0; a < arrayDemo.Length; a++)

{

Random rand = new Random(10);

arrayDemo[a] = a + rand.Next();

}

}

public void PrintArray()

{

int iPos = 1;

foreach (int val in arrayDemo)

{

Console.WriteLine(“Value – ” + Convert.ToString(iPos++) + “: ” + Convert.ToString(val));

}

}

}

Program.cs:

class Program

{

static void Main(string[] args)

{

Console.WriteLine(“\n Original Defined Array Size : “);

IncreaseArraySizeAtRuntime arrSizeAtRuntime = new IncreaseArraySizeAtRuntime();

arrSizeAtRuntime.PrintArray();

Console.WriteLine(“\n Modified Array Size at runtime with Constructor Parameter : “);

IncreaseArraySizeAtRuntime arrSizeAtRuntimeWithParam = new IncreaseArraySizeAtRuntime(10);

arrSizeAtRuntimeWithParam.PrintArray();

Console.Read();

}

}

Program Output:

Image

Happy Coding 🙂

Tagged:

§ 2 Responses to CSharp code equivalent to VB ReDim Preserve

Leave a comment

What’s this?

You are currently reading CSharp code equivalent to VB ReDim Preserve at Gaurav Lal.

meta