To my personal coding style belongs Enumerable.OfType<T>(). I use it everywhere it makes a little bit of sense. Especially IEnumerable<T> allows mighty linqToObject functionallity. I hate the “type-unsafe” looping of ObjectCollections such as the samples below. Now I have some questions about looping across these “UnGenericCollections”.
ConfigurationSectionCollectionHttpModuleCollectionSPBaseCollectionSPFieldCollectionArrayList- so on…
Question 1: If I convert this ArrayList to Enumerable<T> how big is the additional loop in comparison with the simple foreach/if-checks?
var ark = new ArrayList();
ark.Add(new Human());
ark.Add(new Human());
ark.Add(new Animal());
Instead of:
foreach (object passenger in ark)
{
if (passanger is Human) { }
if (passanger is Animal) { }
}
I use:
foreach (var human in ark.OfType<Human>())
{
}
foreach (var animal in ark.OfType<Animal>())
{
}
Question 2: During a foreach loop into a different typed variable, which way of casting/converting will be used? Is this a language feature or does that work out of the box?
foreach (Human human in ark) { }
Thanks for enduring my awful English. Best regards,Benjamin
Ans 1:
In your sample – you may actually be iterating over the FULL enumerable twice.
Ans 2:
It would throw an InvalidCastException exception if there are any non-human in ark.
I would personally prefer
ark.OfTypes<T>(), in case I know I only want to deal withHumanandAnimalsbut would be ignoringElves. This way code is much more cleaner and you are dealing with strongly typed object in your foreach loop.But again in case I do not want to ignore
Elves, I would take rather iterate thru full ArrayList and use casts.