0

I have some rows of code:

public IEnumerable<string> GetCardNames()
    {
        string[]cardname = new string[cards.Count]; 

        for (int i = 0; i < cards.Count; i++)
            cardname[i]=  cards[i].value + " of " + cards[i].suit + "\n";
        return cardname;
    }

What I confused about is why it's a better way to use:

public IEnumerable<string> GetCardNames()

than :

public string[] GetCardNames()

or :

public List<string> GetCardNames()

I have read a lot of answers about IEnumerable but I'm still not feel so clear about this one, I mean the benefit of using IEnumerable in this case.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Frankly, your question is as much a matter of opinion as anything else. And if you really have "read a lot of answers" about the question, but you don't bother to explain what you read and what _exactly_ you're still confused about, you're asking everyone here to go over all that ground again. All that said: one general rule of thumb is to use the least-capable type needed to get the job done, so that your code has maximum reusability for other code that might use it. This obviously applies more in a situation with parameter types and public class memebrs than local variables. – Peter Duniho Jul 27 '17 at 04:06
  • Because `string[]` is tightly coupled to internal details of your method implementation. Say you have an array today, but an update tomorrow wants to use a list instead, or perhaps something even more exotic. If you return IEnumerable instead of array, nothing changes beyond this one method. – Joel Coehoorn Jul 31 '17 at 14:18
  • On the other hand, there's a certain amount of [YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it) here, and there's something to be said for returning a type with more capabilities (like .Length and index lookup) if you already have them. So I don't mind seeing the array value _for the return type_. However, when accepting parameter arguments, you should pretty much **always** prefer IEnumerable. – Joel Coehoorn Jul 31 '17 at 14:21
  • Thanks @Joel Coehoorn , your answers help me a lot – Nguyễn Ngọc Hoàng Aug 02 '17 at 11:18

0 Answers0