How to Increase Size of Array in C#

In this article I am going to explain that how to Increase size of Array.
  • 7878

The .NET Framework allow you to increase the size of an array when you judge it necessary. In C# when you are declaring an array variable, you must provide a constant value as the number of items. There are many situations when we need to increase the size of array. You can increase that number. You can define your own method or function to increase the size of array. 

namespace demo_array

{

    public class Starter

    {

        public class Routine

        {

            public static void IncreaseArray(ref string[] values, int increment)

            {

                string[] array = new string[values.Length + increment];

                values.CopyTo(array, 0);

                values = array;

            }

        }

        private static void Show(string[] ns)

        {

            foreach (string name in ns)

                Console.WriteLine("EmpName: " + name);

        }

        public static void Main()

        {

            string[] names = new string[4];

            Console.WriteLine("Length of Empnames = " + names.Length.ToString());

            Console.WriteLine("");

            names[0] = "Ajay";

            names[1] = "Rajiv";

            names[2] = "Alok";

            names[3] = "Manish";

 

            Show(names);

            Routine.IncreaseArray(ref names, 6);

            Console.WriteLine("\nLength of Empnames = " + names.Length.ToString());

            Console.WriteLine("");

            names[4] = "TATA";

            names[5] = "NANA";

            names[6] = "BABA";

            names[7] = "KAKA";

            names[8] = "BATA";

            names[9] = "DADA";

            Show(names);

            Console.WriteLine("");

            Console.ReadKey(); 

        }

    }  

}


Output

Increasing an Array.gif

Ask Your Question 

Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.