What happens if you have a collection of objects that implement various interfaces and you do a foreach on that collection for a specific interface (which only some members of the collection implement)? Is it possible to skip the members that don’t implement that interface?
interface IFoo {}
interface IBar {}
class Foo : IFoo {}
class Baz : IFoo, IBar {}
…
var foos = new List<IFoo> ();
foos.Add(new Foo());
foos.Add(new Baz());
foreach (IBar bar in foos)
{
// What happens now?
}
Nothing happens now, as you already got an
InvalidCastExceptionin the first row…WHY?
foreachstatements are being translated to something like:There is an implicit cast in the
foreach statementWhich allows you to write stupid things like the following without Compilation time error:
You can use LINQ as suggested by @Erno to get only the objects that implement the
IBarinterface:Which is like: