Foreach Loop

foreach will iterate over any object of a class that implements IEnumerable (take note that IEnumerable inherits from it). Such objects include some built-in ones, but not limit to: List, T[] (arrays of any type), Dictionary, as well as interfaces like IQueryable and ICollection, etc.

syntax

foreach(ItemTypeitemVariableinenumerableObject)statement;

remarks

The type ItemType does not need to match the precise type of the items, it just needs to be assignable from the type of the items

Instead of ItemType, alternatively var can be used which will infer the items type from the enumerableObject by inspecting the generic argument of the IEnumerable implementation

The statement can be a block, a single statement or even an empty statement (;)

If enumerableObject is not implementing IEnumerable, the code will not compile

During each iteration the current item is cast to ItemType (even if this is not specified but compiler-inferred via var) and if the item cannot be cast an InvalidCastException will be thrown.