Create a List With Multiple Different Types in C#

Generally C# is a very strongly typed language and usually lists allow only one defined data type. Using ArrayList, however, we can get around this restriction to some extent.

For example, if we have 3 different classes A, B and C, we can combine them with ArrayList in a list:

class MyClassA { }
class MyClassB { }
class MyClassC { }

ArrayList myList = new ArrayList();
myList.Add(new MyClassA());
myList.Add(new MyClassB());
myList.Add(new MyClassB());
myList.Add(new MyClassA());
myList.Add(new MyClassC());
myList.Add(new MyClassC());

We can now iterate over this list and retrieve the individual elements. However, we then probably need to figure out what type of element it is. This is how it works:

for (int i = 0, len = myList.Count; i < len; i++) {
  switch (myList[i].GetType()) {
    case typeof(MyClassA):
      // Do something with class A elements.
      break;

    case typeof(MyClassB):
      // Do something with class B elements.
      break;

    case typeof(MyClassC):
      // Do something with class C elements.
      break;
  }
}