I’m working with a legacy collection object that only implements non-generic IEnumerable and ICollection. What exactly happens with this object when I try to use this object with a foreach giving a more specific type on the LHS of the foreach expression?
// LegacyFooCollection implements non-generic IEnumerable
LegacyFooCollection collection = GetFooCollection();
foreach (Foo f in collection)
{
// etc.
}
I know (because I’ve tried it) that this is safe when everything in collection really is of type Foo, but what happens if that fails?
The C# compiler performs the cast implicitly for you. In terms of the casting (but only in those terms1) it’s equivalent to:
Note that this will happen with generic collections too:
This is all detailed in section 8.8.4 of the C# 4 spec.
If you’re using .NET 3.5 or higher and you want to only select items of the appropriate type, you can use
Enumerable.OfType:That may not be necessary for a
LegacyFooCollection, but it can be useful when you’re trying to find (say) all theTextBoxcontrols in a form.1 The differences are:
fis read-only; in the “conversion” it’s writablefyou will (currently) capture a single variable across all iterations, as opposed to a separate variable per iteration in the “conversion”