Friday, October 25, 2024

ArrayList Methods & Properties in CSharp

In C#, the ArrayList class is a part of the System.Collections namespace and is a dynamically resizing array implementation. However, it's important to note that ArrayList is less commonly used in modern C# development due to the advent of strongly-typed generic collections like List<T>. 

Methods of the ArrayList class:

1. Add(Object):  Adds an object to the end of the ArrayList.
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("Hello");
2. Insert(Int32, Object): Inserts an element into the ArrayList at the specified index.
    myArrayList.Insert(1, "World");
3. Remove(Object): Removes the first occurrence of a specific object from the ArrayList.
    myArrayList.Remove("Hello");
4. RemoveAt(Int32): Removes the element at the specified index of the ArrayList.
    myArrayList.RemoveAt(0);

5. Clear(): Removes all elements from the ArrayList.

    myArrayList.Clear();
6. Contains(Object): Determines whether the ArrayList contains a specific value.
    bool containsHello = myArrayList.Contains("Hello");
7. IndexOf(Object): Searches for the specified object and returns the zero-based index of the first occurrence within the entire ArrayList.
    int index = myArrayList.IndexOf("World");
 

Properties of the ArrayList class:

1. Count: Gets the number of elements contained in the ArrayList.
    int count = myArrayList.Count;
2. Capacity: Gets or sets the number of elements that the ArrayList can contain.
    int capacity = myArrayList.Capacity;
3. IsFixedSize: Gets a value indicating whether the ArrayList has a fixed size.
    bool isFixedSize = myArrayList.IsFixedSize;
4. IsReadOnly: Gets a value indicating whether the ArrayList is read-only.
    bool isReadOnly = myArrayList.IsReadOnly;
5. Item[Int32]: Gets or sets the element at the specified index.
    object element = myArrayList[0];
Remember that when using ArrayList, since it operates with objects (of type System.Object), you'll need to cast the retrieved objects to their appropriate types when working with them. However, it's often recommended to use the strongly-typed List<T> class for improved type safety and performance.

No comments:

Post a Comment

Hot Topics