Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does resharper suggest: "Return type can be IEnumerable<T>"?

I am new to Resharper and loving it. However, it recently suggested something which didn't make sense to me, and I'm wondering why it made the suggestion. I've disabled it in Resharper, but am wondering if there's something I'm missing...

I wrote a function with a signature: List<string> DoSomething()

Resharper suggested I change this to: IEnumerable<string> DoSomething().

Now I can understand why the parameters of a method must be as generic as possible. It helps the code be more reusable etc. However, I try and make sure the data returned by my methods is specific rather than generic.

Could someone please explain why Resharper suggested what it did?

(To find the rule, go to Resharper Options \ Code Inspection \ Inspection Severity, and search for: "Return type can be IEnumerable".)

like image 558
Omaer Avatar asked Jul 08 '14 12:07

Omaer


People also ask

What is the return type of IEnumerable?

IEnumerable is the return type from an iterator.

What is IEnumerable T in C#?

IEnumerable. IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator, which returns an IEnumerator<T> object. The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property.


1 Answers

There are several reasons why you might want to have a more generic return type.

The more generic type allows you more freedom to change the implementation of the method without changing the method interface. With a return type of IEnumerable<string> you can for example choose to use a string[] instead of a List<string> to produce the return value.

Using a more generic type offers some protection for the data. If the method returns a list that exists as a private member in the class, the person calling the method could change the returned list without realising that it changes the list inside the class. When you return an IEnumerable<string> that can only be used to iterate the items, it doesn't give access to change the list.

It's clearer how the more limited return type should be used. It's natural to assume that an IEnumerable<string> is supposed to be iterated, but a List<string> can be used in many different ways.

like image 179
Guffa Avatar answered Oct 01 '22 03:10

Guffa