.Net framework ArrayList Insert() method allow us to insert an element into the ArrayList at the specified index. this arraylist Insert() method exists under System.Collections namespace. this method require to pass two parameters named ‘index’ and ‘value’.
the ‘index’ parameter value data type is System.Int32. this integer value represents the zero-based index at which ‘value’ should be inserted. the ‘value’ parameter value type is System.Object which represents the Object to insert. the value can be null. this arraylist Insert() method implements as IList.Insert(Int32, Object).
Insert() method throw ArgumentOutOfRangeException exception, if ‘index’ is less than zero or ‘index’ is greater than count. this method also throw NotSupportedException exception, if the arraylist is read-only or the arraylist has a fixed size. arraylist accept null as a valid value and it also allow duplicate elements.
the following console c# example code demonstrate us how can we insert an element into the arraylist at the specified index programmatically at run time in an console application.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Program { static void Main(string[] args) { ArrayList colors = new ArrayList() { "BurlyWood", "Coral", "Indigo", "CadetBlue" }; Console.WriteLine("ArrayList Elements...."); foreach (string color in colors) { Console.WriteLine(color); } colors.Insert(1, "Orchid"); Console.WriteLine(); Console.WriteLine("After call Insert(index 1, object Orchid) Method"); Console.WriteLine("Now ArrayList Elements..."); foreach (string color in colors) { Console.WriteLine(color); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ArrayList Elements.... BurlyWood Coral Indigo CadetBlue After call Insert(index 1, object Orchid) Method Now ArrayList Elements... BurlyWood Orchid Coral Indigo CadetBlue |