Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach in a list [C#]

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

like image 674
Mike John Avatar asked Mar 15 '13 11:03

Mike John


People also ask

Can you use foreach on a list?

forEach statement is a C# generic statement which you can use to iterate over elements of a List.

How do you write a foreach loop in a List C#?

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.

Can we use foreach on list in C#?

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.

Is there a foreach loop in C?

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.


2 Answers

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>())
like image 185
Roman Gruber Avatar answered Oct 04 '22 18:10

Roman Gruber


You can try something like:

foreach(Alpha a in list.Where(x => x is Alpha)) // Alpha is a script. 
  a.doSomething();
like image 42
Maarten Avatar answered Oct 04 '22 17:10

Maarten