.Net framework ArrayList Item property allow us to get or set the element at the specified index. the arraylist Item property exists under System.Collections namespace. this property require to pass a parameter named ‘index’.
the ‘index’ parameter value type is System.Int32. this integer value represents the zero-based index of the element to get or set. this Item property return value type is System.Object which represents the element at the specified index. this arraylist Item property implements as IList.Item.
arraylist Item property throw ArgumentOutOfRangeException exception, if the ‘index’ is less than zero or ‘index’ is equals to or greater than Count. arraylist accepts null as a valid value and arraylist also allow duplicate elements.
the following console c# example code demonstrate us how can we get or set (change) arraylist element 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 27 28 29 | class Program { static void Main(string[] args) { ArrayList colors = new ArrayList() { "Olive", "Indigo", "Violet", "Green", "Yellow" }; Console.WriteLine("ArrayList Elements... "); foreach (string color in colors) { Console.WriteLine(color); } Console.WriteLine("\n"); Console.WriteLine("ArrayList Index 0 Element: " + colors[0]); Console.WriteLine("ArrayList Index 2 Element: " + colors[2]); Console.WriteLine("ArrayList Index 4 Element: " + colors[4]); colors[2] = "Red"; Console.WriteLine("\n"); Console.WriteLine("After Modify ArrayList Index 2 Element... "); 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 16 17 18 19 20 21 | ArrayList Elements... Olive Indigo Violet Green Yellow ArrayList Index 0 Element: Olive ArrayList Index 2 Element: Violet ArrayList Index 4 Element: Yellow After Modify ArrayList Index 2 Element... Olive Indigo Red Green Yellow |