A2oz

What is the Difference Between an ArrayList and a Dictionary in C#?

Published in Programming 2 mins read

An ArrayList in C# is a collection of elements that are stored in a sequential order, while a Dictionary is a collection of key-value pairs.

ArrayList

  • Sequential Order: Elements in an ArrayList are stored in the order they are added.

  • Data Type: An ArrayList can store elements of any data type.

  • Access: You can access elements in an ArrayList using their index, starting from 0.

  • Example:

      ArrayList names = new ArrayList();
      names.Add("John");
      names.Add("Jane");
      names.Add("Peter");
    
      Console.WriteLine(names[1]); // Output: Jane

Dictionary

  • Key-Value Pairs: A Dictionary stores data in key-value pairs. Each key must be unique and is used to access its corresponding value.

  • Data Type: You can specify the data types for both the keys and values.

  • Access: You can access values in a Dictionary using their corresponding keys.

  • Example:

      Dictionary<string, int> ages = new Dictionary<string, int>();
      ages.Add("John", 30);
      ages.Add("Jane", 25);
      ages.Add("Peter", 40);
    
      Console.WriteLine(ages["Jane"]); // Output: 25

Key Differences

Feature ArrayList Dictionary
Data Structure Sequential Key-Value Pairs
Order Preserves order of elements Does not preserve order
Access Index-based Key-based
Uniqueness Elements can be duplicated Keys must be unique
Data Type Any Specified for keys and values

Practical Insights

  • Use an ArrayList when you need to store a collection of data in a specific order and access elements by their index.
  • Use a Dictionary when you need to store data in key-value pairs and access values using their corresponding keys.

Related Articles