ReSharper 2024.1 Help

Code Inspection: Return type can be IEnumerable<T> (private accessibility)

Category

Common Practices and Code Improvements

ID

ReturnTypeCanBeEnumerable.Local

EditorConfig

resharper_return_type_can_be_enumerable_local_highlighting

Default severity

Hint

Language

C#, VB.NET

Requires SWA

No

If a method returns a more generic type, it allows for more flexibility. For example, you can change the method's implementation without the need to update usages.

Also, returning a more generic type may help in the future if you decide to change the return value to a more specific type, for example, List<T>: if callers expect IEnumerable<T>, they will be able to accept List<T>, but not vice versa.

Below, ReSharper suggests changing the return type of GetNumbers() from List<String> to IEnumerable<String>:

Note that such a replacement is not always possible, though. If methods of the derived type are used on the returned object anywhere in the current type, ReSharper will not issue this suggestion.

class EnumerableTDemo { public static void Main() { string output = string.Join(" ", GetNumbers()); Console.WriteLine(output); } private static List<string> GetNumbers() { var Numbers = new List<string> {"1", "2", "3"}; return Numbers; } }
class EnumerableTDemo { public static void Main() { string output = string.Join(" ", GetNumbers()); Console.WriteLine(output); } private static IEnumerable<string> GetNumbers() { var Numbers = new List<string> {"1", "2", "3"}; return Numbers; } }

In some cases, however, returning a more specific type might be better. If a method is intended to work only with a specific type like an Array, and its implementation is unlikely to be changed in the future, you can suppress this inspection for that method.

Last modified: 15 April 2024