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:

foreach (var entry in myList) {
  // Can't use a switch statement here, because cases must be constants.
  if (entry.GetType() == typeof(MyClassA)) {
     // Do something with class A elements.
  }
  else if (entry.GetType() == typeof(MyClassB)) {
    // Do something with class B elements.
  }
  else if (entry.GetType() == typeof(MyClassC)) {
    // Do something with class C elements.
  }
}

#1 Doorlock wrote:

07.10.2022 15:52

typeof does not work while using arraylist

#2 Christian Hanne wrote:

07.10.2022 17:17

Thanks for letting me know, that there is something wrong with my example. typeof does indeed work with ArrayList. But it does not work as a switch-case, because these have to be constants. I think I mixed up my programming languages there. So instead of a switch use if-else-conditions. I will update the article as soon as possible.