Consider the following classes:
class A
{
public virtual string Name { get { return "A"; } }
}
class B : A
{
public override string Name { get { return "B"; } }
}
class C : A
{
public override string Name { get { return "C"; } }
}
And a list containing two objects of type B and one of type C:
List<A> l = new List<A>();
l.Add(new B());
l.Add(new C());
l.Add(new B());
Is there some way to force a check of the type at runtime and iterate only over the objects of type B in this list (short of writing a custom implementation of a list)? Something like:
foreach (B obj in l) // runtime error
Console.WriteLine(obj.Name);
// desired output:
// B
// B
I haven't run into this problem in a project, but the thought just occurred to me and I'm curious if this can be done. I'm aware the need for this feature could indicate a design flaw.