MonoBehavior[] list; // This is from Unity3d but think of it as Object,
// all classes inherit from it.
The list is filled with lots of things, some are Alpha, from the class Alpha, and others are from other classes.
foreach(Alpha a in list) // Alpha is a script.
a.doSomething();
I was under the assumption that my foreach would work this way: Foreach Alpha script found in list do something, ignore every other component.
This is a casting problem, I think. Please help me understand casting/polymorphism better.
I get this error during execution: Cannot cast from source type to destination type
forEach statement is a C# generic statement which you can use to iterate over elements of a List.
C# provides an easy to use and more readable alternative to for loop, the foreach loop when working with arrays and collections to iterate through the items of arrays/collections. The foreach loop iterates through each item, hence called foreach loop. Before moving forward with foreach loop, visit: C# for loop.
In C#, the foreach loop iterates collection types such as Array, ArrayList, List, Hashtable, Dictionary, etc. It can be used with any type that implements the IEnumerable interface.
There is no foreach in C. You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg.
You're going at polymorphism the wrong way around: While Alpha is a derived type, not all other objects in your list of type MonoBehavior are. Hence some will fail the implicit type cast that foreach is doing. You could use the "OfType()" extension if it is available in your environment:
foreach(Alpha a in list.OfType<Alpha>())
You can try something like:
foreach(Alpha a in list.Where(x => x is Alpha)) // Alpha is a script.
a.doSomething();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With