Is it possible to resize an array in C#

CsharpProgrammingServer Side Programming

You cannot resize an array in C#, but using Array.Resize you can replace the array with a new array of different size.

The following is our array −

char[] ch = new char[10];
ch[0] = 'a';
ch[1] = 'b';

Now, resize −

Array.Resize<char>(ref ch, 10);

The following is the complete example −

Example

 Live Demo

using System;
class Program {
   static void Main() {
      char[] ch = new char[10];
      ch[0] = 'a';
      ch[1] = 'b';
      // Resize array
      Array.Resize<char>(ref ch, 10);
      // Set value for new elements
      ch[2] = 'c';
      ch[3] = 'd';
      ch[4] = 'e';
      ch[5] = 'f';
      ch[6] = 'g';
      ch[7] = 'h';
      ch[8] = 'i';
      ch[9] = 'j';
      Console.WriteLine("New Array: "+ new string(ch));
   }
}

Output

New Array: abcdefghij
raja
Published on 04-Sep-2018 11:03:35
Advertisements