C# ArrayList Item

Description

ArrayList Item gets or sets the element at the specified index.

Syntax

ArrayList.Item has the following syntax.


public virtual Object this[
  int index
] { get; set; }

Parameters

ArrayList.Item has the following parameters.

  • index - The zero-based index of the element to get or set.

Example

The following code example creates an ArrayList and adds several items.


/*  ww  w . j a v  a2  s  .c o  m*/

using System;
using System.Collections;

public class Example
{
    public static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ArrayList stringList = new ArrayList();

        stringList.Add("a");
        stringList.Add("abc");
        stringList.Add("abcdef");
        stringList.Add("abcdefg");

        Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);
        stringList[2] = "abcd";
        Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

    }
}

The code above generates the following result.

Example 2

The following example uses the Item property explicitly to assign values to items in the list.


using System;//ww  w.  j  a v a  2s.c  o  m
using System.Collections;

public class ScrambleList : ArrayList
{
    public static void Main()
    {
        ScrambleList integerList = new ScrambleList();

        for (int i = 0; i < 10; i++)
        {
            integerList.Add(i);
        }

        integerList.Scramble();

    }

    public void Scramble()
    {
        int limit = this.Count;
        int temp;
        int swapindex;
        Random rnd = new Random();
        for (int i = 0; i < limit; i++)
        {
            temp = (int)this[i];
            swapindex = rnd.Next(0, limit - 1);
            this[i] = this[swapindex];
            this[swapindex] = temp;
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections »




ArrayList
BitArray
Comparer
Hashtable
Queue
SortedList
Stack