Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq IList interfaces vs concrete

Tags:

c#

linq

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 ??

like image 274
HoopSnake Avatar asked Dec 22 '22 05:12

HoopSnake


2 Answers

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.

like image 116
Jon Skeet Avatar answered Dec 24 '22 00:12

Jon Skeet


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.

like image 31
Reed Copsey Avatar answered Dec 24 '22 02:12

Reed Copsey