Web Design that taps into the haromny and vision of your dreams.

C# Collection Types (Array, List, Dictionary, Hash Table)

By on in Coding

1,116 words, estimated reading time 6 minutes.

Introduction to Programming with C# Series
  1. Introduction to Programming with C# 7
  2. C# Programming Fundamentals
  3. Introduction to Object-Oriented Programming
  4. C# Object-Oriented Programming Part 2
  5. Flow Control and Control Structures in C#
  6. C# Data Types, Variables and Casting
  7. C# Collection Types (Array, List, Dictionary, Hash Table)
  8. C# Operators
  9. Using Data in C# 7 with ADO.Net & Entity Framework
  10. LINQ: .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. Reflection in C#
  14. What Are ASP.Net Webforms
  15. Introduction to ASP.Net MVC
  16. Windows Application Development
  17. Assemblies in C#
  18. Working with Resources Files, Culture & Regions
  19. Regular Expressions in C#
  20. Introduction to XML with C#
  21. Complete Guide to File Handling in C#

As well as common data types such as strings and integers, .Net provides a number of advanced data types which provide a means of utilising common data structures more easily and make life a lot easier for the developer. In this article, we will look at lists, dictionaries, hash tables, and string concatination.

Array

Arrays are used to store collections of data in a numerical indexed list. Arrays can be one-dimensional, multi-dimensional or jagged.

An array is declared using brackets after the data type, with an element count in the brackets. Arrays in C# are of a fixed length, not dynamic. We will cover dynamic arrays (ArrayList and List) later in this tutorial.

int[] myIntArray = new int[10] // Create an array of 10 ints

Note: Although arrays are zero indexed, which means that the first item in the array is 0, the second is 1 and so on, when declaring arrays you specify the total number of elements.

Arrays can be assigned to individually or in a loop:

int[] myIntArray = new int[10];
myIntArray[0] = 0;
myIntArray[1] = 10;
myIntArray[2] = 20;
myIntArray[3] = 30;
 
// Assignment via loop
for (int i=0; i<myIntArray.Length; i++)
{
  myIntArray[i] = i * 10;
}
 
// Foreach loop over array
foreach (int element in myIntArray)
{
  Console.WriteLine("${element}");
}

Arrays can also be assigned to on declaration instead of specifying a length.

int[] myIntArray = {0,1,2,3,4,5,6,7};

Multi-dimensional Arrays

A multi-dimensional array consists of two or more elements that form a matrix. Jagged arrays are multi-dimensional arrays of arrays and covered later.

int myMultiArray = new int[5,5];
int myOtherMultiArray = int[5,2];

Assignment and access are the same as a single dimensional array, but you need to specify both elements.

for (int y=0; y<=5; y++)
{
  for (int x=0; x<=5; x++)
  {
    myMultiArray[x,y] = x * y;
  }
}
 

Jagged Arrays

Jagged arrays, or array of arrays, are multi-dimensional arrays that consist of arrays as the elements.

int[][] myJaggedArray = new int[2][];
 
myJaggedArray[0] = new int[5];
myJaggedArray[1] = new int[] {0, 1, 2, 3, 4, 5, 6, 7}

Array Methods

All arrays are objects that inherit methods and properties from the base Array class. These can be used to determine the number of items in an array (Length) and the number of dimensions (Rank).

Array Lengths

Once an array is declared with a number of elements, its length cannot be changed. If you need more than the number of elements declared you will have to create another array. You cannot re-declare an array in C#.

int[] myIntArray = new int[10];
int[] myLargerIntArray = new int[20];
 
myIntArray.CopyTo(myLargerIntArray, 0);

One solution to this problem is to use a List or an ArrayList, which are much more powerful than simple arrays.

ArrayList

An ArrayList is a class that holds values like an array, but elements can be added or removed at will (dynamic array). They offer greater functionality over an array, but they also have a larger overhead. ArrayLists are not type-safe, meaning that each element of the ArrayList can be of a different type.

using System.Collections.ArrayList;
ArrayList myArrayList = new ArrayList();
Exception ex = new Exception("My Demo Exception");
 
myArrayList.Add("Hello");
myArrayList.Add("World");
myArrayList.Add(10);
myArrayList.Add(ex);
 
foreach (Object obj in myArrayList)
{
  Console.WriteLine(obj.ToString());
}
 
/* Output:
Hello
World
10
System.Exception: My Demo Exception
/*

Lists

A List is a generic type-safe version of an ArrayList. They are defined by specifying the type that they will contain. They can contain only this type of object. The type can be any type of object defined in C# including classes.

using System.Collections.Generic;
 
List<string> myList = new List<string>();
 
myList.Add("Hello");
myList.Add("World");
myList.Add(10); // Compiler Error

Both ArrayList and List support searching and sorting methods.

Hashtables

Hash tables are a named key List where you define a key and a value when setting and getting values. Hash tables are not type-safe, so the key and value are of type object. You can access the data using the named key as the index; however, you will have to check and cast the value.

using System;
using System.Text;
using System.Collections;
 
class Program
{
    static void Main()
    {
        Hashtable myHashTable = new Hashtable();
 
        myHashTable.Add("bob", 27);
        myHashTable.Add(33, "fred");
 
        int theAge = (int)myHashTable["bob"];
    }
}

In order to iterate through hash table elements, you must create a IDictionaryEnumerator interface to retrieve the key and the value.

IDictionaryEnumerator myEnumerator = new myHashTable.GetEnumerator();
 
while (myEnumerator.MoveNext())
{
  Console.WriteLine("{0}: {1}", myEnumerator.Key, myEnumerator.Value);
}

You can also use a foreach loop like this:

foreach (string key in myHashTable.Keys)
{
  Console.WriteLine(key + '=' + myHashTable[key]);
}

Dictionary

A dictionary is a type-safe version of the Hashtable. Like a List<> object, you need to specify the type for both the key and the value.

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        Dictionary<string, int> myDictionary = new Dictionary<string, int>();
 
        myDictionary.Add("bob", 27);
        myDictionary.Add("fred", 33);
 
        int theAge = myDictionary["bob"];
    }
}

StringBuilder

A string data type is an immutable type; meaning that once it is created it cannot be changed. Strange, you may think, I do that all the time...

string name = "Stan";
name = name + " Smith";
name += " Jr";

While the compiler sees no problems with this, it's not the most efferent method. Since the string object cannot be changed, the CLR will create a new string object; assign it the value of the old one plus the extra data, then dispose of the old object. If you are doing multiple operations, such as building up a result string, then this method represents a performance overhead that can be eliminated by using a StringBuilder.

StringBuilder allows the string to be manipulated without objects being created and disposed of each time. They can then be converted back to a string when needed.

StringBuilder myStringBuilder = new StringBuilder();
 
myStringBuilder.Append("bob");
myStringBuilder.Append(" smith");
myStringBuilder.Append(" jr");
 
string myString = myStringBuilder.ToString();

There is a huge performance hit when appending to a string and the speed increase from using a string builder is surprising. You can have a look at the performance increase by running this short piece of code. It will append a full stop to the previous string 100000 times.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = "";
            StringBuilder mySb = new StringBuilder();
 
            Console.WriteLine("String Start: {0}", System.DateTime.Now);
 
            for (int i = 0; i < 100000; i++)
            {
                myString += ".";
            }
 
            Console.WriteLine("String End: {0}", System.DateTime.Now);
            Console.WriteLine("StringBuilder Start: {0}", System.DateTime.Now);
 
            for (int i = 0; i < 100000; i++)
            {
                mySb.Append(".");
            }
 
            Console.WriteLine("StringBuilder End: {0}", System.DateTime.Now);
        }
    }
}
 
String Start: 11/11/2011 20:57:56
String End: 11/11/2011 20:58:12
StringBuilder Start: 11/11/2011 20:58:12
StringBuilder End: 11/11/2011 20:58:12
Press any key to continue . . .

Last updated on: Thursday 11th October 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

Anne-Marie Armour

Anne-Marie Armour

My C# Express will not accept ...
int[] myIntArray = int[10];

It insists that I use the "new" keyword ...
int[] myIntArray = new int[10];

And it insists that ...
int myMultiArray = int[5,5];
int myOtherMultiArray = int[5,2];
becomes ...
int[,] myMultiArray = new int[5,5];
int[,] myOtherMultiArray = new int[5,2];

Reply to Anne-Marie Armour

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.