We’ve talked a bit about the DotNet framework, which basically acts as a little starter kit to help us make our programs. Most of the framework includes useful classes and functions that would be a huge pain to go without. Some examples we’ve seen so far are:

  • Console class (for input/output using the console)
  • Random class (for generating random numbers)
  • File class (for reading text to/from files)

There’s another useful category of things we haven’t talked about yet. These are the data structure classes, which are used frequently for handling data in larger applications.

The first we’ll talk about is the List.

List

using System.Collections.Generic;
 
class Program
{
	static void Main()
	{
		List<int> numbers = new List<int>();
		numbers.Add(5);
		numbers.Add(87);
		numbers.Add(23);
	}
}

Lists are similar to arrays. Under the hood they’re much more complex, but they’re nearly as easy to interact with in your code.

But why use a List instead of an array?

Features of Lists:

  • Can dynamically add and remove items at runtime (meaning the SPACE too!)
  • Can resize itself efficiently as needed
  • Can handle any kind of data type (similar to arrays)

So how is this different from an array? Well, you can’t resize arrays, and you can’t “delete” an element from an array. You can replace the data with something else, but you can’t get rid of the SPACE taken up by that array element; arrays are ALWAYS the same size.

Say you were making a game that can have different kinds of particle effects that spawn/despawn all the time. If you used an array to hold the particles, what size should it be? 1,000? 100,000? With a list, you don’t have to worry about that! A list will GROW as you fill it, and SHRINK as you remove items from it! It resizes to fit the needs of the application.

Common list operations include:

  • List.Add (adding elements)
  • Setting the value of elements at a particular index (array syntax)
  • List.Count (getting the number of things in the list)
  • List.Contains (checking if an item is in the list)
  • List.Remove (removing items from the list)
  • List.Clear (erasing all items from the list)
  • Looping through a list (though we check Count, not Length)

There are other useful built-in operations for lists as well!