2
Answers

Dfference between an Array and ArrayList in dotnet framework

Photo of Kiran Kumar

Kiran Kumar

1w
325
1

Difference between an Array and ArrayList in dotnet framework

Answers (2)

1
Photo of Vishal Yelve
105 17.5k 643.5k 1w
Feature Array ArrayList
Type Safety Strongly typed Weakly typed (stores object)
Resizable ? Fixed size ? Automatically resizes
Performance Faster (no boxing/unboxing) Slower (boxing/unboxing for value types)
Generics Support ? (Use T[]) ? (Use List<T> instead)
Usage Recommendation Use for fixed-size, typed data Use List<T> instead of ArrayList

 

Conceptual Differences

?? 1. Array

  • Declared with a specific type and fixed size.

  • Example:
     

    int[] numbers = new int[3];
    numbers[0] = 1;
    numbers[1] = 2;
    

     

  • Benefits:

    • Type safety (compile-time checking).

    • Better performance for value types.

  • Limitations:

    • Size is fixed after creation.

    • Can't mix different data types.

 

2. ArrayList

  • Part of System.Collections (non-generic).

  • Stores elements as object, allowing mixed types (not recommended).

  • Example:
     

    ArrayList list = new ArrayList();
    list.Add(1);          // boxed int
    list.Add("hello");    // string
    

    Drawbacks:

  • Boxing/unboxing overhead with value types.

  • No compile-time type checking.

 Example Comparison

// Array (strongly typed)
int[] ages = new int[2];
ages[0] = 25;
ages[1] = 30;

// ArrayList (weakly typed)
ArrayList data = new ArrayList();
data.Add(25);        // boxed
data.Add("John");    // allowed, but dangerous
int age = (int)data[0];  // requires casting

 

Should You Use ArrayList?
No — use List<T> instead (from System.Collections.Generic).

List<int> list = new List<int>();
list.Add(10);  // no boxing
int num = list[0];  // no casting needed


In Summary:
 

Use Case Recommended Type
Fixed-size, performance-critical Array
Dynamic, type-safe collection List<T>
Legacy non-generic collections ArrayList (not recommended)
0
Photo of Sangeetha S
213 9k 327.1k 1w

 

Feature Array ArrayList
Size Fixed Dynamic
Type Safety Yes (strongly typed) No (stores object)
Performance Faster (no boxing) Slower (boxing/unboxing)
Generic Support No (use List<T> instead) No (use List<T> instead)
Use Case Known size, type-safe Mixed types, dynamic size