Now with
IList<string> listOfStrings = (new string[] { "bob","mary"});
We can not preform
listOfStrings.ToList().ForEach(i => i.DoSome(i)));
We need to reshape to the concrete implementation of the Interface
List<string> listOfStrings = ((new string[] { "bob","mary"}).ToLIst();
Then we can do a for each
listOfStrings.ForEach(i => i.DoSome(i)));
Is this because the foreach operator does not work with the IList Interface and why is this ??
You're not using the foreach operator - you're using a ForEach method, which is declared on List<T> (here) and also for arrays. There's no such extension method on IList<T> or IEnumerable<T>. You could write one, but personally I'd use a real foreach loop:
foreach (var text in listOfStrings)
{
...
}
See Eric Lippert's blog post on the topic for thoughts that are rather more lucid than mine.
The ForEach method is List<T>.ForEach. It is not a method defined on IList<T>.
However, your first example actually does work:
listOfStrings.ToList().ForEach(i => i.DoSome(i)));
The Enumerable.ToList method returns a List<T>, which allows the above to actually work fine.
You could not do, however:
// Will fail at compile time listOfStrings.ForEach(i => i.DoSome(i)));
As this is using the IList<T> directly, which doesn't have a ForEach method defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With