Craig
Craig

Reputation: 18684

Resharper says I shouldn't use List<T>

I have a method:

static void FileChangesDetected(List<ChangedFiles> files)

I used Visual Studio 2010 and Resharper. Resharper always recommends that I change the List<T> to IEnumerable<T>, and I'm wondering why this is.

In the method, I simply do this:

 foreach (var file in files)
 { ... }

Is there a benefit of using IEnumerable<T> rather than List<T>?

Upvotes: 26

Views: 1636

Answers (5)

Achim
Achim

Reputation: 15702

If you are just iterating of your files, then it does not have to be a List<>. Your code would also work with an array. Or more general: It will work with anything you can iterate over. That's expressed by IEnumerable<>. So the usage of List<> restricts the usage of you message without any need. The ReSharper method is just a hint for that.

Upvotes: 3

Oded
Oded

Reputation: 498972

It all has to do with LSP (Liskov substitution principle).

Basically, instead of using implementations, it is better to code to abstractions.

In this specific case, if all you do is loop over the list, you can use IEnumerable<T> as the simplest abstraction - this way you don't have to use a List<T>, but any collection type in your function.

This allows your functions to be more reusable and reduces coupling.

Upvotes: 29

Simon Mourier
Simon Mourier

Reputation: 138841

Because in your code, you only use the fact that files is an IEnumerable<ChangedFiles>, you don't use for example Count, nor Add.

Even if later on, you want to use List specific methods (with Add or Count methods), it's always better to use an interface: IList<ChangedFiles> instead of a concrete implementation.

Upvotes: 2

Alex Aza
Alex Aza

Reputation: 78457

Resharper suggests that your method doesn't need really require List<T> as a parameter and can easily work with IEnumerable<T>. Which means that you can make you method more generic.

Upvotes: 3

killebytes
killebytes

Reputation: 980

You will still be able to the foreach even if you change it to

IEnumerable<ChangedFiles>

or

ICollection<ChangedFiles>

Upvotes: 1

Related Questions