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.
}
}
There are no comments yet.