C#.NET has a lot of different data structures, for example, one of the most common ones is an Array. However C# comes with many more basic data structures. Choosing the correct data structure to use is part of writing a well structured and efficient program.
In this article I will go over the built-in C# data structures, including the new ones introduces in C#.Net 3.5. Note that many of these data structures apply for other programming languages.
The perhaps simplest and most common data structure is the array. A C# array is basically a list of objects. Its defining traits are that all the objects are the same type and there is a specific number of them. A C# array is defined like this:
[object type][] myArray = new [object type][number of elements]
Some examples:
int[] myIntArray = new int[5]; int[] myIntArray2 = { 0, 1, 2, 3, 4 };
As you can see from the example above, an array can defined empty or with preset elements.
The C# data structure, ArrayList, is a dynamic array. What that means is an ArrayList can have any amount of objects and of any type.
(Under the hood, the ArrayList is an Object array that is expanded as more items are added.)
ArrayList myArrayList = new ArrayList(); myArrayList.Add(56); myArrayList.Add("String"); myArrayList.Add(new Form());
The downside to the ArrayList data structure is one must cast the retrived values back into their original type:
int arrayListValue = (int)myArrayList[0];
The List C# data structure is in short a typed ArrayList. By that I mean it is too a dynamic array, but the different between a List and ArrayList is the List data structure must contain the same type of objects:
List<int> intList = new List<int>(); intList.Add(45); intList.Add(34);
Since the List<> object is tailored to a specific data type, there is no need to cast when retrieving values:
int listValue = intList[0];
For primative data types (int, bool, etc.) using a List is much faster than ArrayList.
Now for a completely different type of C# data structure, the LinkedList. A LinkedList is a series of objects which instead of having their references indexed (like an Array), stay together by linking to each other, in Nodes.
A LinkedList Node has basically three values: the Object's Value, a reference to the Next node, and a reference to the Previous Node.
What is the point of such C# data structure? Well, adding values to the middle of the list is extremely fast compared to any other Array type of data structure. It also keeps memory costs down to a minimum. Lists on the other hand use extra space to make future insertions as fast as possible.
LinkedList<int> list = newLinkedList<int>(); list.AddLast(6);
Retrieving a value is not as straight forward:
list.First.Value or
list.Last.Value
With that we can move on to more complex data structures...
Continue C# Data Structures - Page 2
Dictionary, Hashtable, HashSet >>>